target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
src/svg-icons/maps/add-location.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsAddLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/>
</SvgIcon>
);
MapsAddLocation = pure(MapsAddLocation);
MapsAddLocation.displayName = 'MapsAddLocation';
export default MapsAddLocation;
|
src/svg-icons/action/camera-enhance.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCameraEnhance = (props) => (
<SvgIcon {...props}>
<path d="M9 3L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2h-3.17L15 3H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-1l1.25-2.75L16 13l-2.75-1.25L12 9l-1.25 2.75L8 13l2.75 1.25z"/>
</SvgIcon>
);
ActionCameraEnhance = pure(ActionCameraEnhance);
ActionCameraEnhance.displayName = 'ActionCameraEnhance';
ActionCameraEnhance.muiName = 'SvgIcon';
export default ActionCameraEnhance;
|
templates/rubix/demo/src/routes/BarColSeries.js | jeffthemaximum/Teachers-Dont-Pay-Jeff | import React from 'react';
import {
Row,
Col,
Panel,
PanelBody,
PanelContainer,
} from '@sketchpixy/rubix';
class Chart extends React.Component {
render() {
return (
<PanelContainer>
<Panel>
<PanelBody style={{padding: 25}}>
<div id={this.props.id}></div>
</PanelBody>
</Panel>
</PanelContainer>
);
}
}
export default class BarColSeries extends React.Component {
componentDidMount() {
(() => {
var chart = new Rubix('#single-series-column-chart', {
height: 300,
title: 'Single Series Column Chart',
subtitle: 'Fruits',
titleColor: '#D71F4B',
subtitleColor: '#D71F4B',
axis: {
x: {
type: 'ordinal',
},
y: {
type: 'linear',
tickFormat: 'd'
}
},
tooltip: {
color: '#D71F4B',
format: {
y: '.0f'
}
},
margin: {
left: 50
},
grouped: false,
show_markers: true
});
var fruits = chart.column_series({
name: 'Fruits',
color: '#D71F4B'
});
fruits.addData([
{x: 'Apples', y: 5},
{x: 'Oranges', y: 3},
{x: 'Pears', y: 4},
{x: 'Grapes', y: 7},
{x: 'Bananas', y: 2},
{x: 'Strawberry', y: 15}
]);
})();
(() => {
var chart = new Rubix('#single-series-bar-chart', {
height: 300,
title: 'Single series bar chart',
titleColor: '#E299B7',
subtitle: 'Fruits',
subtitleColor: '#E299B7',
axis: {
x: {
type: 'ordinal',
},
y: {
type: 'linear',
tickFormat: 'd'
}
},
tooltip: {
color: '#E299B7',
format: {
y: '.0f'
}
},
grouped: false,
show_markers: true
});
var fruits = chart.bar_series({
name: 'Fruits',
color: '#E299B7',
marker: 'square'
});
fruits.addData([
{x: 'Apples1', y: 5},
{x: 'Oranges1', y: 3},
{x: 'Pears1', y: 4},
{x: 'Grapes1', y: 7},
{x: 'Bananas1', y: 2},
{x: 'Strawberry1', y: 15}
]);
})();
(() => {
var chart = new Rubix('#grouped-multi-series-column-chart', {
title: 'Grouped multi series column chart',
subtitle: 'Sales by Sales Persons [2006 - 2007]',
titleColor: '#2EB398',
subtitleColor: '#2EB398',
height: 300,
axis: {
x: {
type: 'ordinal',
},
y: {
type: 'linear',
tickFormat: 'd'
}
},
tooltip: {
color: '#2EB398',
format: {
y: '.0f'
}
},
grouped: true,
show_markers: true
});
var year2006 = chart.column_series({
name: '2006',
color: '#2EB398'
});
year2006.addData([
{x: 'Amy Alberts', y: 1000},
{x: 'David Campbell', y: 1170},
{x: 'Garret Young', y: 660},
{x: 'Jae Pak', y: 1030}
]);
var year2007 = chart.column_series({
name: '2007',
color: '#7CD5BA'
});
year2007.addData([
{x: 'Amy Alberts', y: 2000},
{x: 'David Campbell', y: 5170},
{x: 'Garret Young', y: 160},
{x: 'Jae Pak', y: 2030}
]);
})();
(() => {
var chart = new Rubix('#grouped-multi-series-bar-chart', {
title: 'Grouped multi series bar chart',
subtitle: 'Company Performance [2004 - 2007]',
titleColor: '#EE682F',
subtitleColor: '#EE682F',
height: 300,
axis: {
x: {
type: 'ordinal',
},
y: {
type: 'linear',
tickFormat: 'd'
}
},
tooltip: {
color: '#EE682F',
format: {
y: '.0f'
}
},
grouped: true,
show_markers: true
});
var sales = chart.bar_series({
name: 'Sales',
color: '#FFC9A0'
});
sales.addData([
{x: 2004, y: 1000},
{x: 2005, y: 1170},
{x: 2006, y: 660},
{x: 2007, y: 1030}
]);
var expenses = chart.bar_series({
name: 'Expenses',
color: '#EE682F'
});
expenses.addData([
{x: 2004, y: 400},
{x: 2005, y: 460},
{x: 2006, y: 1120},
{x: 2007, y: 540}
]);
})();
(() => {
var chart = new Rubix('#stacked-multi-series-column-chart', {
title: 'Stacked Multi Series Column chart',
subtitle: 'Total fruit consumption',
titleColor: '#EA7882',
subtitleColor: '#EA7882',
height: 300,
axis: {
x: {
type: 'ordinal'
},
y: {
type: 'linear',
tickFormat: 'd',
label: 'Total fruit consumption'
}
},
tooltip: {
color: 'white',
format: {
y: '.0f'
}
},
show_markers: true
});
var john = chart.column_series({
name: 'John',
color: '#EA7882'
});
john.addData([
{x: 'Apples', y: 5},
{x: 'Oranges', y: 3},
{x: 'Pears', y: 4},
{x: 'Grapes', y: 7},
{x: 'Bananas', y: 2}
]);
var jane = chart.column_series({
name: 'Jane',
color: '#79B0EC',
marker: 'square'
});
jane.addData([
{x: 'Apples', y: 2},
{x: 'Oranges', y: 2},
{x: 'Pears', y: 3},
{x: 'Grapes', y: 2},
{x: 'Bananas', y: 1}
]);
var joe = chart.column_series({
name: 'Joe',
color: '#55C9A6',
marker: 'diamond'
});
joe.addData([
{x: 'Apples', y: 3},
{x: 'Oranges', y: 4},
{x: 'Pears', y: 4},
{x: 'Grapes', y: 2},
{x: 'Bananas', y: 5}
]);
})();
(() => {
var chart = new Rubix('#stacked-multi-series-bar-chart', {
title: 'Stacked Multi series bar chart',
subtitle: 'Total fruit consumption',
titleColor: '#C36849',
subtitleColor: '#C36849',
height: 500,
axis: {
x: {
type: 'ordinal'
},
y: {
type: 'linear',
tickFormat: 'd',
label: 'Total fruit consumption'
}
},
tooltip: {
color: '#C36849',
format: {
y: '.0f'
}
},
show_markers: true
});
var john = chart.bar_series({
name: 'John',
color: '#3E5F90'
});
john.addData([
{x: 'Apples', y: 5},
{x: 'Oranges', y: 3},
{x: 'Pears', y: 4},
{x: 'Grapes', y: 7},
{x: 'Bananas', y: 2}
]);
var jane = chart.bar_series({
name: 'Jane',
color: '#C67055',
marker: 'square'
});
jane.addData([
{x: 'Apples', y: 2},
{x: 'Oranges', y: 2},
{x: 'Pears', y: 3},
{x: 'Grapes', y: 2},
{x: 'Bananas', y: 1}
]);
var joe = chart.bar_series({
name: 'Joe',
color: '#E69E8F',
marker: 'diamond'
});
joe.addData([
{x: 'Apples', y: 3},
{x: 'Oranges', y: 4},
{x: 'Pears', y: 4},
{x: 'Grapes', y: 2},
{x: 'Bananas', y: 5}
]);
})();
(() => {
var chart = new Rubix('#stacked-multi-series-column-chart-negative', {
title: 'Stacked column chart with negative values',
subtitle: 'Profit/Expense chart',
titleColor: '#0080FF',
subtitleColor: '#0080FF',
height: 300,
axis: {
x: {
type: 'ordinal'
},
y: {
type: 'linear',
tickFormat: ',.0f',
label: 'Revenue'
}
},
tooltip: {
color: 'white',
format: {
y: ',.0f'
}
},
show_markers: true
});
var profit = chart.column_series({
name: 'Profit',
color: '#0080FF'
});
profit.addData([
{x: 'Jan', y: 30000},
{x: 'Feb', y: 25000},
{x: 'Mar', y: 25000},
{x: 'Apr', y: 30000},
{x: 'May', y: 35000},
{x: 'Jun', y: 15000}
]);
var expenses = chart.column_series({
name: 'Expense',
color: '#FF6666',
marker: 'square'
});
expenses.addData([
{x: 'Jan', y: -25000},
{x: 'Feb', y: -10000},
{x: 'Mar', y: -10000},
{x: 'Apr', y: -15000},
{x: 'May', y: -15000},
{x: 'Jun', y: -5000}
]);
})();
(() => {
var chart = new Rubix('#stacked-multi-series-bar-chart-negative', {
title: 'Stacked bar chart with negative values',
subtitle: 'Profit/Expense chart',
titleColor: '#0080FF',
subtitleColor: '#0080FF',
height: 300,
axis: {
x: {
type: 'ordinal'
},
y: {
type: 'linear',
tickFormat: ',.0f',
label: 'Revenue',
tickCount: 5
}
},
tooltip: {
color: 'white',
format: {
y: ',.0f'
}
},
show_markers: true
});
var profit = chart.bar_series({
name: 'Profit',
color: '#0080FF'
});
profit.addData([
{x: 'Jan', y: 30000},
{x: 'Feb', y: 25000},
{x: 'Mar', y: 25000},
{x: 'Apr', y: 30000},
{x: 'May', y: 65000},
{x: 'Jun', y: 15000}
]);
var expenses = chart.bar_series({
name: 'Expense',
color: '#FF6666',
marker: 'square'
});
expenses.addData([
{x: 'Jan', y: -35000},
{x: 'Feb', y: -10000},
{x: 'Mar', y: -10000},
{x: 'Apr', y: -15000},
{x: 'May', y: -15000},
{x: 'Jun', y: -5000}
]);
})();
}
render() {
return (
<div>
<Row>
<Col sm={12}>
<Chart id='single-series-column-chart' />
<Chart id='single-series-bar-chart' />
<Chart id='grouped-multi-series-column-chart' />
<Chart id='grouped-multi-series-bar-chart' />
<Chart id='stacked-multi-series-column-chart' />
<Chart id='stacked-multi-series-bar-chart' />
<Chart id='stacked-multi-series-column-chart-negative' />
<Chart id='stacked-multi-series-bar-chart-negative' />
</Col>
</Row>
</div>
);
}
}
|
ajax/libs/jquery/1.7.1/jquery.min.js | miketheman/cdnjs | /*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},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(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},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(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); |
examples/src/components/MultiSelectField.js | daviferreira/react-select | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var MultiSelectField = React.createClass({
displayName: 'MultiSelectField',
propTypes: {
label: React.PropTypes.string,
},
getInitialState () {
return {
disabled: false,
value: []
};
},
handleSelectChange (value, values) {
logChange('New value:', value, 'Values:', values);
this.setState({ value: value });
},
toggleDisabled (e) {
this.setState({ 'disabled': e.target.checked });
},
render () {
var ops = [
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Caramel', value: 'caramel' },
{ label: 'Cookies and Cream', value: 'cookiescream' },
{ label: 'Peppermint', value: 'peppermint' }
];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select multi={true} disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={ops} onChange={this.handleSelectChange} />
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} />
<span className="checkbox-label">Disabled</span>
</label>
</div>
</div>
);
}
});
module.exports = MultiSelectField; |
components/__tests__/StyledText-test.js | flyerq/movie-list | import 'react-native';
import React from 'react';
import { MonoText } from '../StyledText';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(<MonoText>Snapshot test!</MonoText>).toJSON();
expect(tree).toMatchSnapshot();
});
|
ajax/libs/forerunnerdb/1.3.49/fdb-legacy.min.js | CyrusSUEN/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("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":4,"../lib/Core":5,"../lib/Document":8,"../lib/Grid":9,"../lib/Highchart":10,"../lib/OldView":25,"../lib/OldView.Bind":24,"../lib/Overview":28,"../lib/Persist":30,"../lib/View":33}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.synthesize(e.prototype,"primaryKey"),d.mixin(e.prototype,"Mixin.Sorting"),e.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},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.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},e.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},e.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},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":32}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a){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._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if("dropped"===this._state)return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),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._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.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'ForerunnerDB.Collection "'+this.name()+'": 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=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),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);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.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},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.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'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.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=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw'ForerunnerDB.Collection "'+this.name()+'": Cannot update cast to unknown type: '+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f,g,h,i,j,k,l=this;if(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(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};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);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},1))},n.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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)},n.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=[],i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;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)},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!1;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"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},n.prototype.subsetOf=function(){return this.__subsetOf},n.prototype._subsetOf=function(a){return this.__subsetOf=a,this},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.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},n.prototype.find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L={},M=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(a,b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup,C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(M)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(M)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),void 0!==b.$page&&void 0!==b.$limit&&(L.page=b.$page,L.pages=Math.ceil(e.length/b.$limit),L.records=e.length,b.$page&&b.$limit>0&&(C.data("cursor",L),e.splice(0,b.$page*b.$limit))),b.$skip&&(L.skip=b.$skip,e.splice(0,b.$skip),C.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(L.limit=b.$limit,e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e.$cursor=L,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},n.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}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},n.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'ForerunnerDB.Collection "'+this.name()+'": $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)},n.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.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(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=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._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},n.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},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default: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"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection 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},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e);break;case"update":e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f);break;case"remove":e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)}})},"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!"}}),n.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({object:function(a){return 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=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection with undefined name!'}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},d.finishModule("Collection"),b.exports=n},{"./Crc":6,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":27,"./Path":29,"./ReactorIO":31,"./Shared":32}],4:[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"),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"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){
if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": 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=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);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(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),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":3,"./Shared":32}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a){this.init.apply(this,arguments)};h.prototype.init=function(){this._db={},this._debug={}},h.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()}},"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()}}}),h.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},h.moduleLoaded=h.prototype.moduleLoaded,h.version=h.prototype.version,h.shared=d,h.prototype.shared=d,d.addModule("Core",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),h.prototype._isServer=!1,h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.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=h},{"./Db.js":7,"./Metrics.js":14,"./Overload":27,"./Shared":32}],6:[function(a,b,c){"use strict";var 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}();b.exports=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}},{}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a){this.init.apply(this,arguments)};j.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},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()}},"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"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.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"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=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=d.concat("string"===e?c.peek(a):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("dropped"!==this._state){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._core._db[this._name]}return!0},"function":function(a){if("dropped"!==this._state){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._core._db[this._name]}return!0},"boolean":function(a){if("dropped"!==this._state){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._core._db[this._name]}return!0},"boolean, function":function(a,b){if("dropped"!==this._state){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._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a).core(this),this._db[a]},e.prototype.databases=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._db)this._db.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,collectionCount:this._db[b].collections().length}):c.push({name:b,collectionCount:this._db[b].collections().length}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},b.exports=j},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":14,"./Overload":27,"./Shared":32}],8:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared"),function(){var c=function(){this.init.apply(this,arguments)};c.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",c),d.mixin(c.prototype,"Mixin.Common"),d.mixin(c.prototype,"Mixin.Events"),d.mixin(c.prototype,"Mixin.ChainReactor"),d.mixin(c.prototype,"Mixin.Constants"),d.mixin(c.prototype,"Mixin.Triggers"),e=a("./Collection"),f=d.modules.Db,d.synthesize(c.prototype,"state"),d.synthesize(c.prototype,"db"),d.synthesize(c.prototype,"name"),c.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;return this},c.prototype.update=function(a,b,c){this.updateObject(this._data,b,a,c)},c.prototype.updateObject=e.prototype.updateObject,c.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},c.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log('ForerunnerDB.Document: Setting data-bound document property "'+b+'" for collection "'+this.name()+'"')):(a[b]=c,this.debug()&&console.log('ForerunnerDB.Document: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"'))},c.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},c.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log('ForerunnerDB.Document: Moving data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"'))},c.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)},c.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},c.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},c.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},c.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])},c.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},c.prototype._updatePop=function(a,b){var c,d=!1;return a.length>0&&(this._linked?(1===b?c=a.length-1:-1===b&&(c=0),c>-1&&(window.jQuery.observable(a).remove(c),d=!0)):1===b?(a.pop(),d=!0):-1===b&&(a.shift(),d=!0)),d},c.prototype.drop=function(){return"dropped"===this._state?!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),!0):!1},f.prototype.document=function(a){return a?(this._document=this._document||{},this._document[a]=this._document[a]||new c(a).db(this),this._document[a]):this._document},f.prototype.documents=function(){var a,b=[];for(a in this._document)this._document.hasOwnProperty(a)&&b.push({name:a});return b},d.finishModule("Document"),b.exports=c}()},{"./Collection":3,"./Shared":32}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b){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"),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},l.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(){return"dropped"===this._state?!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("ForerunnerDB.Grid: Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!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).attr("data-grid-sort")||"",d=c.split(","),e={};for(b=0;b<d.length;b++)e[d]=1;this._from.orderBy(e),this.emit("sort",e)},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)};b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._from.link(a._selector,a.template(),{$wrap:"gridRow"}),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query&&b.find("[data-grid-filter]").each(function(c,d){d=window.jQuery(d);var e,f,g=d.attr("data-grid-filter"),h={},i=d.html(),j=a._db.view("tmpGridFilter_"+a._id+"_"+g);h[g]=1,j.query({$distinct:h}).orderBy(h).from(a._from),f=['<div class="dropdown" id="'+a._id+"_"+g+'">','<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">',i+' <span class="caret"></span>',"</button>",'<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">',"</ul>","</div>"],e=window.jQuery(f.join("")),d.html(e),j.link(e.find("ul"),{template:'{^{for options}}<li role="presentation"><a role="menuitem" tabindex="-1" href="#" data-val="{{:'+g+'}}">{^{if active}}<span class="glyphicons glyphicons-tick"></span> {{/if}}{{:'+g+"}}</a></li>{{/for}}"},{$wrap:"options"}),b.on("click","#"+a._id+"_"+g+" ul.dropdown-menu li>a",function(b){b.preventDefault();var c={};c[g]=window.jQuery(this).attr("data-val"),a._from.queryAdd(c)})}),a.emit("refresh")}return this},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(this._db._grid[a])throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot create a grid using this collection/view because a grid with this name already exists: '+name;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}},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'ForerunnerDB.Collection/View "'+this.name()+'": Cannot remove a grid using this collection/view 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('ForerunnerDB.Collection/View "'+this.name()+'": 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("Db.Grid: 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("Db.Grid: 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=[];for(a in this._grid)this._grid.hasOwnProperty(a)&&b.push({name:a,count:this._grid[a].count()});return b},d.finishModule("Grid"),b.exports=l},{"./Collection":3,"./CollectionGroup":4,"./ReactorIO":31,"./Shared":32,"./View":33}],10:[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'ForerunnerDB.Highchart "'+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.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw'ForerunnerDB.Highchart "'+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.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){var e,f,g,h,i,j,k=this._collection.distinct(a),l=[],m={categories:[]};for(i=0;i<k.length;i++){for(e=k[i],f={},f[a]=e,h=[],g=this._collection.find(f,{orderBy:d}),j=0;j<g.length;j++)m.categories.push(g[j][b]),h.push(g[j][c]);l.push({name:e,data:h})}return{xAxis:m,series:l}},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,arguments)})},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);for(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(){return"dropped"!==this._state?(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),!0):!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({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":27,"./Shared":32}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),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("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=new(f.create(2,this.sortAsc)),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,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},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){return this._data[this._itemHash(a,this._keys)]||[]},g.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}},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.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":29,"./Shared":32}],12:[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._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.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.finishModule("IndexHashMap"),b.exports=f},{"./Path":29,"./Shared":32}],13:[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,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return 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":32}],14:[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":26,"./Shared":32}],15:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={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]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},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},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}])},b.exports=d},{"./Overload":27}],18:[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},{}],19:[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}}),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;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":27}],20:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)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],f,d));h++);if(g){if("or"===c)return!0}else n=!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],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)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],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){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"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{},d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],21:[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},{}],22:[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._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},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._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=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),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":27}],23:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_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('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_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=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":32}],25:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":3,"./CollectionGroup":4,"./Shared":32}],26:[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":29,"./Shared":32}],27:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["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},{}],28:[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._collections=[],this._collectionDroppedWrap=function(){b._collectionDropped.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"),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._collections},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._collections.length;)this._removeCollection(this._collections[0]);return this._addCollection(a),this},h.prototype._addCollection=function(a){return-1===this._collections.indexOf(a)&&(this._collections.push(a),a.chain(this),a.on("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._removeCollection=function(a){var b=this._collections.indexOf(a);return b>-1&&(this._collections.splice(a,1),a.unChain(this),a.off("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._collectionDropped=function(a){a&&this._removeCollection(a)},h.prototype._refresh=function(){if("dropped"!==this._state){if(this._collections&&this._collections[0]){this._collData.primaryKey(this._collections[0].primaryKey());var a,b=[];for(a=0;a<this._collections.length;a++)b=b.concat(this._collections[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(){if("dropped"!==this._state){for(this._state="dropped",delete this._data,delete this._collData;this._collections.length;)this._removeCollection(this._collections[0]);delete this._collections,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this)}return!0},e.prototype.overview=function(a){return a?(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},d.finishModule("Overview"),b.exports=h},{"./Collection":3,"./Document":8,"./Shared":32}],29:[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.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 f.push(b?{path:g,value:a[d]}:{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]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},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.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.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":32}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("localforage");k=function(){this.init.apply(this,arguments)},k.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),n.config({driver:[n.INDEXEDDB,n.WEBSQL,n.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),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,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":n.setDriver(n.LOCALSTORAGE);break;case"WEBSQL":n.setDriver(n.WEBSQL);break;case"INDEXEDDB":n.setDriver(n.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 n.driver()},k.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){n.setItem(a,d).then(function(a){c&&c(!1,a)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d)}else b&&b(!1,a)},this.mode()){case"localforage":n.getItem(a).then(function(a){e(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":n.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(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._name)}f.apply(this)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):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;this._name?this._db?this._db.persist.load(this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){this.persist=new k(this),i.apply(this,arguments)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":3,"./CollectionGroup":4,"./Shared":32,localforage:41}],31:[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||!b.chainReceive)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"dropped"!==this._state&&(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)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":32}],32:[function(a,b,c){"use strict";var d={version:"1.3.49",modules:{},_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.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:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},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:a("./Overload"),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")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":27}],33:[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._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f("__FDB__view_privateData_"+this._name)},d.addModule("View",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"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor"),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.find=function(a,b){return this.publicData().find(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket()}return this},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(a.type){case"setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(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++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0):!1},l.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db},l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.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()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.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},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.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)}},l.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),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.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._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},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'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;var d=new l(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){return this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.View: Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a]},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b=[];for(a in this._view)this._view.hasOwnProperty(a)&&b.push({name:a,count:this._view[a].count()});return b},d.finishModule("View"),b.exports=l},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":31,"./Shared":32}],34:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++c<b;)a[c]();b=g.length}h=!1}}function e(){}var f=b.exports={},g=[],h=!1;f.nextTick=function(a){g.push(a),h||setTimeout(d,0)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=e,f.addListener=e,f.once=e,f.off=e,f.removeListener=e,f.removeAllListeners=e,f.emit=e,f.binding=function(a){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(a){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}],35:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:37}],36:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":35,asap:37}],37:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:34}],38:[function(a,b,c){(function(){"use strict";function c(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new o(function(a,d){var e=p.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(){e.result.createObjectStore(c.storeName)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function e(a,b){var c=this,d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=a(c.value,c.key,h++);void 0!==d?b(d):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new o(function(c,e){d.ready().then(function(){var f=d._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),h=g.objectStore(f.storeName);null===b&&(b=void 0);var i=h.put(b,a);g.oncomplete=function(){void 0===b&&(b=null),c(b)},g.onabort=g.onerror=function(){e(i.error)}})["catch"](e)});return m(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(a){var b=a.target.error;"QuotaExceededError"===b&&d(b)}})["catch"](d)});return m(d,b),d}function h(a){var b=this,c=new o(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(){c(g.error)}})["catch"](c)});return m(c,a),c}function i(a){var b=this,c=new o(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 l(c,a),c}function j(a,b){var c=this,d=new o(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 l(d,b),d}function k(a){var b=this,c=new o(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 l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function m(a,b){b&&a.then(function(a){n(b,a)},function(a){b(a)})}function n(a,b){return a?setTimeout(function(){return a(null,b)},0):void 0}var o="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,p=p||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(p){var q={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports?b.exports=q:"function"==typeof define&&define.amd?define("asyncStorage",function(){return q}):this.asyncStorage=q}}).call(window)},{promise:36}],39:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.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=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.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(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":42,promise:36}],40:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(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 e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){
c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(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 m(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 m(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 m(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="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":42,promise:36}],41:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.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},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){if(n===l.DEFINE)return void a([f],function(a){i._extend(a),c()});if(n===l.EXPORT){var k;switch(f){case i.INDEXEDDB:k=a("./drivers/indexeddb");break;case i.LOCALSTORAGE:k=a("./drivers/localstorage");break;case i.WEBSQL:k=a("./drivers/websql")}i._extend(k)}else i._extend(q[f])}else{if(!h[f])return i._driverSet=g.reject(j),void d(j);i._extend(h[f])}c()}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":38,"./drivers/localstorage":39,"./drivers/websql":40,promise:36}],42:[function(a,b,c){(function(){"use strict";function a(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,f=g;a instanceof ArrayBuffer?(d=a,f+=i):(d=a.buffer,"[object Int8Array]"===c?f+=k:"[object Uint8Array]"===c?f+=l:"[object Uint8ClampedArray]"===c?f+=m:"[object Int16Array]"===c?f+=n:"[object Uint16Array]"===c?f+=p:"[object Int32Array]"===c?f+=o:"[object Uint32Array]"===c?f+=q:"[object Float32Array]"===c?f+=r:"[object Float64Array]"===c?f+=s:b(new Error("Failed to get type for BinaryArray"))),b(f+e(d))}else if("[object Blob]"===c){var h=new FileReader;h.onload=function(){var a=e(this.result);b(g+j+a)},h.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(t){window.console.error("Couldn't convert value into a JSON string: ",a),b(null,t)}}function c(a){if(a.substring(0,h)!==g)return JSON.parse(a);var b=a.substring(t),c=a.substring(h,t),e=d(b);switch(c){case i:return e;case j:return new Blob([e]);case k:return new Int8Array(e);case l:return new Uint8Array(e);case m:return new Uint8ClampedArray(e);case n:return new Int16Array(e);case p:return new Uint16Array(e);case o:return new Int32Array(e);case q:return new Uint32Array(e);case r:return new Float32Array(e);case s:return new Float64Array(e);default:throw new Error("Unkown type: "+c)}}function d(a){var b,c,d,e,g,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=f.indexOf(a[b]),d=f.indexOf(a[b+1]),e=f.indexOf(a[b+2]),g=f.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&g;return k}function e(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=f[c[b]>>2],d+=f[(3&c[b])<<4|c[b+1]>>4],d+=f[(15&c[b+1])<<2|c[b+2]>>6],d+=f[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 f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g="__lfsc__:",h=g.length,i="arbf",j="blob",k="si08",l="ui08",m="uic8",n="si16",o="si32",p="ur16",q="ui32",r="fl32",s="fl64",t=h+i.length,u={serialize:a,deserialize:c,stringToBuffer:d,bufferToString:e};"undefined"!=typeof b&&b.exports?b.exports=u:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return u}):this.localforageSerializer=u}).call(window)},{}]},{},[1]); |
src/components/OrderForm.js | OpenCollective/frontend | import React from 'react';
import PropTypes from 'prop-types';
import { pick, get } from 'lodash';
import { withApollo } from 'react-apollo';
import { Button, Col, Form, FormGroup, Row } from 'react-bootstrap';
import colors from '../constants/colors';
import TierComponent from './Tier';
import InputField from './InputField';
import MatchingFundWithData from './MatchingFundWithData';
import ActionButton from './Button';
import SectionTitle from './SectionTitle';
import CreateOrganizationForm from './CreateOrganizationForm';
import withIntl from '../lib/withIntl';
import { defineMessages, FormattedMessage, FormattedDate, FormattedTime } from 'react-intl';
import { capitalize, formatCurrency, isValidEmail, getEnvVar } from '../lib/utils';
import { getPaypal } from '../lib/paypal';
import { getStripeToken } from '../lib/stripe';
import { getRecaptcha, getRecaptchaSiteKey } from '../lib/recaptcha';
import { checkUserExistence, signin } from '../lib/api';
import { paymentMethodLabelWithIcon } from '../lib/payment_method_label';
class OrderForm extends React.Component {
static propTypes = {
order: PropTypes.object.isRequired, // { tier: {}, quantity: Int, interval: String, totalAmount: Int }
collective: PropTypes.object.isRequired,
LoggedInUser: PropTypes.object,
onSubmit: PropTypes.func,
matchingFund: PropTypes.string,
redeemFlow: PropTypes.bool,
intl: PropTypes.object,
client: PropTypes.object,
};
constructor(props) {
super(props);
const { intl, order } = props;
const tier = { ...order.tier };
this.state = {
isNewUser: true,
loginSent: false,
user: {},
fromCollective: {},
paymentMethod: { type: 'creditcard' }, // the default payment method is "creditcard"
creditcard: {
show: !this.props.redeemFlow,
save: true,
},
orgDetails: {
show: false,
},
/* Set by loadPayPalButton(). This field stores the data from
the authorization so we can ask the user's confirmation
before processing the payment. */
paypalOrderRequest: null,
order: order || {},
result: {},
recaptchaToken: null,
};
this.state.order.totalAmount = this.state.order.totalAmount || tier.amount * (tier.quantity || 1);
this.paymentMethodsOptions = [];
this.allowOrganizations = order.tier.type !== 'TICKET';
this.messages = defineMessages({
'order.contributeAs': {
id: 'tier.order.contributeAs',
defaultMessage: 'Contribute as',
},
'order.rsvpAs': { id: 'tier.order.rsvpAs', defaultMessage: 'RSVP as' },
'order.profile.myself': {
id: 'tier.order.profile.myself',
defaultMessage: 'myself',
},
'order.success': {
id: 'tier.order.success',
defaultMessage: '🎉 Your order has been processed successfully',
},
'order.error': {
id: 'tier.order.error',
defaultMessage: "An error occured 😳. The order didn't go through. Please try again in a few.",
},
'order.button': {
id: 'tier.order.button',
defaultMessage: 'place order',
},
'order.organization.create': {
id: 'tier.order.organization.create',
defaultMessage: 'create an organization',
},
'order.profile.logout': {
id: 'tier.order.profile.logout',
defaultMessage: 'logout to create a new profile',
},
'error.email.invalid': {
id: 'error.email.invalid',
defaultMessage: 'Invalid email address',
},
'paymentmethod.label': {
id: 'paymentmethod.label',
defaultMessage: 'Payment Method',
},
'creditcard.label': {
id: 'creditcard.label',
defaultMessage: 'Credit Card',
},
'creditcard.save': {
id: 'creditcard.save',
defaultMessage: 'Save credit card to {type, select, user {my account} other {{type} account}}',
},
'creditcard.missing': {
id: 'creditcard.missing',
defaultMessage: 'Credit card missing',
},
'creditcard.error': {
id: 'creditcard.error',
defaultMessage: 'Invalid credit card',
},
'newcreditcard.label': {
id: 'newcreditcard.label',
defaultMessage: 'Credit Card',
},
'paymentMethod.type': {
id: 'paymentMethod.type',
defaultMessage: 'Payment Type',
},
'paymentMethod.creditcardOrGiftcard': {
id: 'paymentMethod.creditcardOrGiftcard',
defaultMessage: 'Credit Card / Gift Card',
},
'paymentMethod.bitcoin': {
id: 'paymentMethod.bitcoin',
defaultMessage: 'bitcoin',
},
'paymentMethod.paypal': {
id: 'paymentMethod.paypal',
defaultMessage: 'Paypal',
},
'paymentMethod.manual': {
id: 'paymentMethod.manual',
defaultMessage: 'bank transfer',
},
'ticket.title': { id: 'tier.order.ticket.title', defaultMessage: 'RSVP' },
'backer.title': {
id: 'tier.order.backer.title',
defaultMessage: 'Become a {name}',
},
'sponsor.title': {
id: 'tier.order.sponsor.title',
defaultMessage: 'Become a {name}',
},
'type.label': { id: 'tier.type.label', defaultMessage: 'type' },
'firstName.label': {
id: 'user.firstName.label',
defaultMessage: 'first name',
},
'lastName.label': {
id: 'user.lastName.label',
defaultMessage: 'last name',
},
'company.label': { id: 'user.company.label', defaultMessage: 'company' },
'website.label': { id: 'user.website.label', defaultMessage: 'website' },
'twitterHandle.label': {
id: 'user.twitterHandle.label',
defaultMessage: 'twitter',
},
'twitterHandle.description': {
id: 'user.twitterHandle.description',
defaultMessage: 'If any',
},
'email.label': { id: 'user.email.label', defaultMessage: 'email' },
'email.description': {
id: 'user.email.description',
defaultMessage: '* required',
},
'email.description.login': {
id: 'signin.login.description',
defaultMessage: 'Welcome back! Click on "Login" (or hit Enter) and we will send you a link to login by email.',
},
'email.description.signup': {
id: 'signin.emailSent.description',
defaultMessage: 'Login email sent. Please follow the instructions in that email to proceed.',
},
'description.label': {
id: 'user.description.label',
defaultMessage: 'Short bio',
},
'description.description': {
id: 'user.description.description',
defaultMessage: 'Present yourself in 60 characters or less, if you can!',
},
'totalAmount.label': {
id: 'tier.totalAmount.label',
defaultMessage: 'Total amount',
},
'startsAt.label': {
id: 'tier.startsAt.label',
defaultMessage: 'start date and time',
},
'endsAt.label': {
id: 'tier.endsAt.label',
defaultMessage: 'end date and time',
},
'order.error.organization.name.required': {
id: 'order.error.organization.name.required',
defaultMessage: 'Please provide a name for the new organization',
},
'order.error.organization.website.required': {
id: 'order.error.organization.website.required',
defaultMessage: 'Please provide a website for the new organization',
},
'order.publicMessage.placeholder': {
id: 'order.publicMessage.placeholder',
defaultMessage: 'Use this space to add a personal message (public)',
},
'newsletterOptIn.description': {
id: 'user.newsletterOptIn.description',
defaultMessage: 'Subscribe to the Open Collective newsletter.',
},
});
this.fields = [
{
name: 'firstName',
maxLength: 127,
},
{
name: 'lastName',
maxLength: 128,
},
{
name: 'company',
maxLength: 255,
},
{
name: 'website',
maxLength: 255,
},
{
name: 'twitterHandle',
pre: '@',
maxLength: 255,
validate: val => val.match(/^[A-Za-z0-9_]{1,15}$/),
},
{
name: 'description',
maxLength: 255,
},
];
this.fields = this.fields.map(field => {
if (this.messages[`${field.name}.label`]) {
field.label = intl.formatMessage(this.messages[`${field.name}.label`]);
}
if (this.messages[`${field.name}.description`]) {
field.description = intl.formatMessage(this.messages[`${field.name}.description`]);
}
return field;
});
this.populateProfiles();
}
componentDidMount() {
this._isMounted = true;
this.UNSAFE_componentWillReceiveProps(this.props);
this.fetchRecaptchaToken();
}
UNSAFE_componentWillReceiveProps(props) {
const { LoggedInUser } = props;
if (!LoggedInUser) return;
if (!this._isMounted) return; // Fixes error: Can only update a mounted or mounting component
this.setState({ LoggedInUser, isNewUser: !LoggedInUser });
this.populateProfiles(LoggedInUser);
setTimeout(() => this.selectProfile(LoggedInUser.CollectiveId), 0); // need to pass a cycle to let setState take effect
}
// All the following methods are arrow functions and auto-bind
fetchRecaptchaToken = () => {
getRecaptcha()
.then(recaptcha => {
recaptcha.ready(() => {
recaptcha.execute(getRecaptchaSiteKey(), { action: 'OrderForm' }).then(recaptchaToken => {
this.setState({ recaptchaToken });
});
});
})
.catch(err => {
console.log('Recaptcha error', err);
});
};
/** Interval set either in the tier or in the order object */
interval = () => this.state.order.interval || get(this.state, 'order.tier.interval');
/** Populate the combo of payment methods */
populatePaymentMethodTypes = host => {
const { intl } = this.props;
const paymentMethodTypeOptions = [
{
creditcard: intl.formatMessage(this.messages['paymentMethod.creditcardOrGiftcard']),
},
];
/* We only support paypal for one time donations to the open
source collective for now. */
if (host.id === 11004 && this.interval() === null) {
paymentMethodTypeOptions.push({
payment: intl.formatMessage(this.messages['paymentMethod.paypal']),
});
}
// Add the option to pay by wire transfer for the BrusselsTogether host
if (get(host, 'settings.paymentMethods.manual') && !this.interval()) {
paymentMethodTypeOptions.push({
manual:
get(host, 'settings.paymentMethods.manual.title') ||
intl.formatMessage(this.messages['paymentMethod.manual']),
});
}
this.paymentMethodTypeOptions = paymentMethodTypeOptions;
};
paymentMethodsOptionsForCollective = (paymentMethods, collective) => {
const { intl } = this.props;
return paymentMethods.map(pm => {
const value = pm.uuid;
const label = paymentMethodLabelWithIcon(intl, pm, collective.name);
return { [value]: label };
});
};
populatePaymentMethods = CollectiveId => {
const { LoggedInUser } = this.props;
let paymentMethodsOptions = [];
const collective = this.collectivesById[CollectiveId];
const filterPMs = pms =>
(pms || []).filter(
pm =>
pm.service === 'stripe' ||
pm.service === 'paypal' ||
(pm.service === 'opencollective' && ['prepaid', 'collective', 'virtualcard'].includes(pm.type)),
);
if (collective) {
const paymentMethods = filterPMs(collective.paymentMethods);
paymentMethodsOptions = this.paymentMethodsOptionsForCollective(paymentMethods, collective);
}
if (LoggedInUser && CollectiveId !== LoggedInUser.CollectiveId) {
const userCollective = this.collectivesById[LoggedInUser.CollectiveId];
const paymentMethods = filterPMs(LoggedInUser.collective.paymentMethods);
paymentMethodsOptions = [
...paymentMethodsOptions,
...this.paymentMethodsOptionsForCollective(paymentMethods, userCollective),
];
}
if (paymentMethodsOptions.length > 0) {
paymentMethodsOptions.push({ other: '➕ \xA0\xA0New Credit Card' });
}
this.paymentMethodsOptions = paymentMethodsOptions;
};
/**
* Populate the profiles available based on the current logged in user
* If the tier is a ticket, you can only order the ticket as an individual
* Otherwise, you can order a tier as an individual or as any organization that you are an admin of
* @param {*} LoggedInUser
*/
populateProfiles = LoggedInUser => {
const { intl } = this.props;
const fromCollectiveOptions = [],
collectivesById = {};
if (LoggedInUser) {
fromCollectiveOptions.push({
[LoggedInUser.CollectiveId]: LoggedInUser.collective.name,
});
collectivesById[LoggedInUser.CollectiveId] = LoggedInUser.collective;
LoggedInUser.memberOf.map(membership => {
if (membership.collective.type === 'COLLECTIVE' && membership.role !== 'ADMIN') return;
if (membership.collective.type === 'EVENT') return;
if (membership.collective.type === 'ORGANIZATION' && !this.allowOrganizations) return;
if (['ADMIN', 'HOST'].indexOf(membership.role) === -1) return;
const value = get(membership, 'collective.id');
const label = get(membership, 'collective.name');
collectivesById[value] = pick(membership.collective, ['id', 'type', 'name', 'paymentMethods']);
fromCollectiveOptions.push({ [value]: label });
});
} else {
fromCollectiveOptions.push({
myself: intl.formatMessage(this.messages['order.profile.myself']),
});
}
if (this.allowOrganizations) {
fromCollectiveOptions.push({
organization: intl.formatMessage(this.messages['order.organization.create']),
});
} else if (LoggedInUser) {
fromCollectiveOptions.push({
logout: intl.formatMessage(this.messages['order.profile.logout']),
});
}
this.collectivesById = collectivesById;
this.fromCollectiveOptions = fromCollectiveOptions;
};
logout = () => {
window.localStorage.removeItem('accessToken');
window.localStorage.removeItem('LoggedInUser');
window.location.replace(window.location.href);
};
selectProfile = profile => {
if (profile === 'logout') {
return this.logout();
}
const CollectiveId = isNaN(profile) ? null : profile;
const collective = CollectiveId && this.collectivesById[CollectiveId];
let fromCollective = {};
if (collective) {
fromCollective = {
id: CollectiveId,
type: collective.type,
name: collective.name,
};
}
const newState = {
...this.state,
fromCollective,
orgDetails: {
show: Boolean(profile === 'organization'),
},
creditcard: {
show: true,
},
};
if (collective) {
this.populatePaymentMethods(CollectiveId);
if (this.paymentMethodsOptions.length > 0) {
// The data structure looks like that:
// [
// { "8222e069-e4b0-4409-9563-167fa078fdaa" => "John Doe - Visa 4242 - exp 10/2018" },
// { "3944a1fe-0878-4832-ab33-c493f536152e" => "John Doe - Visa 4343 - exp 11/2019" }
// ]
const uuid = Object.keys(this.paymentMethodsOptions[0])[0];
// NOTE: might be fragile to have { show: undefined } as a result
newState.creditcard = { uuid: uuid };
} else {
newState.creditcard = { show: true, save: true }; // reset to default value
}
}
this.setState(newState);
if (typeof window !== 'undefined') {
window.state = newState;
}
};
handleChange = (obj, attr, value) => {
this.resetError();
const newTier = { ...this.state.order.tier };
const newOrder = { ...this.state.order };
const newState = Object.assign({}, this.state, {
order: newOrder,
tier: newTier,
});
if (value === 'null') {
value = null;
}
if (value !== undefined) {
newState[obj][attr] = value;
} else if (attr === null) {
newState[obj] = {};
} else {
newState[obj] = Object.assign({}, this.state[obj], attr);
}
if (obj === 'creditcard' && attr.uuid === 'other') {
newState.creditcard.show = true;
}
if (attr === 'tier') {
newState.order.totalAmount = newState.order.tier.amount * (newState.order.tier.quantity || 1);
if (newState.order.tier.quantity) {
newState.order.quantity = newState.order.tier.quantity;
}
// when the user selects a tier with an interval, we set the default payment method type to credit card
// which is the only one that supports recurring payments
if (newState.order.tier.hasOwnProperty('interval')) {
newState.order.interval = newState.order.tier.interval;
if (newState.order.interval) {
newState.paymentMethod.type = 'creditcard';
}
}
}
if (attr === 'email') {
checkUserExistence(value).then(exists => {
this.setState({ isNewUser: !exists });
});
}
this.setState(newState, () => {
if (typeof window !== 'undefined') {
window.state = newState;
}
/* This is the type of the PayPal payment method */
if (this.isPayPalSelected()) {
this.loadPayPalButton();
}
});
};
/** Return true if PayPal is the selected payment method
*
* Because the way the Payment Method combo works we dont't really
* have a better way to find out which option is selected. At some
* point it'd be nice to save `service.type` instead of just `type`.
*/
isPayPalSelected = () => this.state.paymentMethod.type === 'payment';
/** Return true if the user has authorized a PayPal payment
*
* After the user authenticates & authorizes the payment using the
* checkout button, PayPal will send us a token with the
* authorization. This function returns `true` if the token is
* available.
*/
isPayPalAuthorized = () => !!this.state.paypalOrderRequest;
/** Create the PayPal Checkout button and setup payment parameters
*
* This method is called when PayPal is selected as the payment
* provider. It creates the PayPal button and hooks it up to the
* backend methods that create and execute the payment.
*/
loadPayPalButton = async () => {
const button = document.getElementById('paypal-checkout');
/* Destroy any already created button */
button.innerHTML = '';
/* Convert amount to what PayPal accepts (dollars) */
const amount = this.getTotalAmount() / 100;
/* We need some information about the order to create the PayPal
payment object. */
const orderRequest = this.prepareOrderRequest();
/* Parameters for the paypal button */
const renderOptions = {
env: getEnvVar('PAYPAL_ENVIRONMENT'),
commit: true,
payment: async (data, actions) => {
const paymentURL = '/api/services/paypal/create-payment';
const { id } = await actions.request.post(paymentURL, {
amount,
currency: orderRequest.currency,
});
return id;
},
onAuthorize: async data => {
/* We'll send the order to the backend but we need to inject
the extra information needed by PayPal somewhere. And the
chosen place was the data field in the PaymentMethod
entry. */
orderRequest.paymentMethod.data = data;
/* Using the PayPal field as the token for this payment
method. */
orderRequest.paymentMethod.token = data.paymentToken;
/* Corrects the `service.type' identification info */
orderRequest.paymentMethod.service = 'paypal';
orderRequest.paymentMethod.type = 'payment';
return this.submitOrder(orderRequest);
},
};
try {
const paypal = await getPaypal();
paypal.Button.render(renderOptions, '#paypal-checkout');
} catch (error) {
console.error(error);
} finally {
button.removeAttribute('disabled');
}
};
getTotalAmount = () => {
const { order } = this.state;
const quantity = get(order, 'tier.quantity') || order.quantity || 1;
const total = quantity * order.tier.amount || order.totalAmount;
return total;
};
prepareOrderRequest = () => {
const { paymentMethod, order, fromCollective, user, recaptchaToken } = this.state;
const { currency } = order.tier || this.props.collective;
const quantity = get(order, 'tier.quantity') || order.quantity || 1;
const orderRequest = {
user,
quantity,
currency,
paymentMethod,
fromCollective,
recaptchaToken,
collective: { id: this.props.collective.id },
publicMessage: order.publicMessage,
interval: order.interval || order.tier.interval,
totalAmount: this.getTotalAmount(),
matchingFund: order.matchingFund,
};
if (order.tier && order.tier.id) {
orderRequest.tier = { id: order.tier.id, amount: order.tier.amount };
}
return orderRequest;
};
/** Call the underlying onSubmit method with an order request */
submitOrder = async orderRequest => {
await this.props.onSubmit(orderRequest || this.prepareOrderRequest());
// Refetch a Recaptcha Token because one can only be used once
this.fetchRecaptchaToken();
};
/** Submit order built with PayPal payment method */
submitPayPalOrder = async () => this.submitOrder(this.state.paypalOrderRequest);
handleSubmit = async () => {
if (!(await this.validate())) return false;
this.setState({ loading: true });
try {
await this.submitOrder();
} finally {
this.setState({ loading: false });
}
};
error = msg => {
const error = `${msg}`;
this.setState({ result: { error } });
};
resetError = () => {
this.setState({ result: { error: null } });
};
validate = async () => {
const TEST_ENVIRONMENT =
typeof window !== 'undefined' &&
window.location.search.match(/test=e2e/) &&
(window.location.hostname === 'staging.opencollective.com' || window.location.hostname === 'localhost');
const { intl } = this.props;
const { order, user, paymentMethod, creditcard } = this.state;
const newState = { ...this.state };
// validate email
if (this.state.isNewUser && !isValidEmail(user.email)) {
this.setState({
result: {
error: intl.formatMessage(this.messages['error.email.invalid']),
},
});
return false;
}
const required = (obj, attrPath, messageId) => {
if (!get(obj, attrPath)) {
throw new Error(intl.formatMessage(this.messages[messageId]));
}
};
// validate new org
if (this.state.orgDetails.show) {
try {
required(this.state, 'fromCollective.name', 'order.error.organization.name.required');
required(this.state, 'fromCollective.website', 'order.error.organization.website.required');
} catch (e) {
this.setState({ result: { error: e.message } });
return false;
}
}
// validate payment method
if (order.totalAmount > 0 && paymentMethod.type !== 'manual') {
if (creditcard.uuid && creditcard.uuid.length === 36) {
newState.paymentMethod = { uuid: creditcard.uuid };
this.setState(newState);
return true;
} else if (get(newState, 'paymentMethod.type') === 'manual') {
return true;
} else {
let res;
if (!creditcard.addEventListener && !TEST_ENVIRONMENT) {
this.error(intl.formatMessage(this.messages['creditcard.missing']));
return false;
}
try {
res = await getStripeToken('cc', creditcard);
} catch (e) {
console.log('>>> error: ', typeof e, e);
this.error(e);
return false;
}
const last4 = res.card.last4;
const paymentMethod = {
name: last4,
token: res.token,
service: 'stripe',
type: 'creditcard',
data: {
fullName: res.card.full_name,
expMonth: res.card.exp_month,
expYear: res.card.exp_year,
brand: res.card.brand,
country: res.card.country,
funding: res.card.funding,
zip: res.card.address_zip,
},
save: true,
};
newState.paymentMethod = paymentMethod;
this.setState(newState);
return true;
}
}
return true;
};
resetOrder = () => {
this.setState({ order: {} });
};
signin = () => {
signin(this.state.user, `${window.location.pathname}${window.location.search}`).then(() => {
this.setState({ loginSent: true });
});
};
renderPayPalButton = () =>
!this.isPayPalAuthorized() && (
<FormGroup controlId="paypalFG" id="paypalFG">
<div>
<Col sm={2} />
<Col sm={10}>
<div id="paypal-checkout" />
</Col>
</div>
</FormGroup>
);
renderDisclaimer = values => {
return (
<div className="disclaimer">
<style jsx>
{`
.disclaimer {
margin: 0.5rem;
font-size: 1.2rem;
}
`}
</style>
<FormattedMessage
id="collective.host.disclaimer"
defaultMessage="By clicking above, you are pledging to give the host ({hostname}) {amount} {interval, select, month {per month} year {per year} other {}} for {collective}."
values={values}
/>
{values.interval && (
<div>
<FormattedMessage id="collective.host.cancelanytime" defaultMessage="You can cancel anytime." />
</div>
)}
</div>
);
};
renderCreditCard = () => {
const { intl } = this.props;
const { creditcard } = this.state;
const showNewCreditCardForm = creditcard.show && (!creditcard.uuid || creditcard.uuid === 'other');
return (
<Row>
<Col sm={12}>
{this.paymentMethodsOptions && this.paymentMethodsOptions.length > 1 && (
<InputField
type="select"
className="horizontal"
label={intl.formatMessage(this.messages['paymentmethod.label'])}
name="creditcardSelector"
onChange={uuid => this.handleChange('creditcard', { uuid })}
options={this.paymentMethodsOptions}
/>
)}
{showNewCreditCardForm && (
<div>
<InputField
label={intl.formatMessage(this.messages['newcreditcard.label'])}
type="creditcard"
name="creditcard"
className="horizontal"
onChange={creditcardObject => this.handleChange('creditcard', creditcardObject)}
/>
</div>
)}
</Col>
</Row>
);
};
render() {
const { intl, collective, LoggedInUser } = this.props;
const { order, fromCollective } = this.state;
const currency = (order.tier && order.tier.currency) || collective.currency;
this.populatePaymentMethodTypes(collective.host);
const requireLogin = !this.state.isNewUser && !LoggedInUser;
const inputEmail = {
type: 'email',
name: 'email',
focus: true,
required: true,
label: `${intl.formatMessage(this.messages['email.label'])}*`,
description: intl.formatMessage(this.messages['email.description']),
defaultValue: order['email'],
onChange: value => this.handleChange('user', 'email', value),
};
if (!this.state.isNewUser) {
inputEmail.button = (
<Button onClick={this.signin} focus={true}>
Login
</Button>
);
if (!this.state.loginSent) {
inputEmail.description = intl.formatMessage(this.messages['email.description.login']);
} else {
inputEmail.button = <Button disabled={true}>Login</Button>;
inputEmail.description = intl.formatMessage(this.messages['email.description.signup']);
}
}
return (
<div className="OrderForm">
<style jsx global>
{`
.ocCard span {
max-width: 350px;
}
.OrderForm span.input-group,
.OrderForm .help-block {
max-width: 500px;
}
.OrderForm textarea[name='publicMessage'] {
height: 10rem;
}
`}
</style>
<style jsx>
{`
.OrderForm {
margin: 0 auto;
}
.userDetailsForm {
overflow: hidden;
}
.paymentDetails {
overflow: hidden;
}
.OrderForm :global(.tier) {
margin: 0 0 1rem 0;
}
label {
max-width: 100%;
padding-right: 1rem;
}
.result {
margin-top: 3rem;
}
.result div {
width: 100%;
}
.error {
color: red;
font-weight: bold;
}
.value {
padding-top: 7px;
display: inline-block;
}
p {
margin-top: -2.5rem;
color: #737373;
}
.gift-card-expander {
color: ${colors.blue};
margin-left: 205px;
}
.info {
margin-top: 3px;
}
.manualPaymentMethod .instructions {
max-width: 50rem;
}
.manualPaymentMethod :global(code) {
display: block;
color: black;
border: 1px solid #99c2ff;
background: #ebf3ff;
}
#paypal-checkout {
padding-top: 30px;
}
.form-group#paypalFG {
margin-bottom: 0px !important;
}
.submit {
display: flex;
align-items: center;
}
.pleasewait {
margin-left: 2rem;
font-size: 1.4rem;
}
`}
</style>
<Form horizontal>
<section className="userDetailsForm">
<SectionTitle
section="userDetails"
subtitle={
<div>
{order.tier.type !== 'TICKET' && !LoggedInUser && (
<FormattedMessage
id="tier.order.userdetails.description"
defaultMessage="If you wish to remain anonymous, only provide an email address without any other personal details."
/>
)}
{order.tier.type !== 'TICKET' && LoggedInUser && (
<FormattedMessage
id="tier.order.userdetails.description.loggedin"
defaultMessage="If you wish to remain anonymous, logout and use another email address without providing any other personal details."
/>
)}
</div>
}
/>
{!LoggedInUser && (
<Row key="email.input">
<Col sm={12}>
<InputField className="horizontal" {...inputEmail} />
</Col>
</Row>
)}
{!LoggedInUser &&
this.state.isNewUser &&
this.fields.map(field => (
<Row key={`${field.name}.input`}>
<Col sm={12}>
<InputField
className="horizontal"
{...field}
defaultValue={this.state.user[field.name]}
onChange={value => this.handleChange('user', field.name, value)}
/>
</Col>
</Row>
))}
{!requireLogin && this.fromCollectiveOptions.length > 1 && (
<InputField
className="horizontal"
type="select"
label={intl.formatMessage(
this.messages[order.tier.type === 'TICKET' ? 'order.rsvpAs' : 'order.contributeAs'],
)}
name="fromCollectiveSelector"
onChange={CollectiveId => this.selectProfile(CollectiveId)}
options={this.fromCollectiveOptions}
defaultValue={get(order, 'fromCollective.id')}
/>
)}
{!LoggedInUser && this.state.isNewUser && (get(collective, 'tags') || []).includes('open source') && (
<Row key="newsletterOptIn.input">
<Col sm={12}>
<InputField
className="horizontal"
name="newsletterOptIn"
type="checkbox"
help="Receive our monthly newsletter with updates about new collectives and features. Stay in the know with the latest sponsor and backer funding leaderboard, open source inspiration, and upcoming events."
description={intl.formatMessage(this.messages['newsletterOptIn.description'])}
defaultValue={this.state.user['newsletterOptIn']}
onChange={value => this.handleChange('user', 'newsletterOptIn', value)}
/>
</Col>
</Row>
)}
</section>
{!fromCollective.id && this.state.orgDetails.show && (
<CreateOrganizationForm onChange={org => this.handleChange('fromCollective', org)} />
)}
{!requireLogin && (
<div>
<section className="order">
{order.tier.type !== 'TICKET' && <SectionTitle section="contributionDetails" />}
{order.tier.type === 'TICKET' && (
<div>
<SectionTitle section="ticketDetails" />
<Row>
<Col sm={12}>
<div className="form-group">
<label className="col-sm-2 control-label">
<FormattedMessage id="tier.order.ticket.info" defaultMessage="Event info" />
</label>
<Col sm={10}>
<div className="info">
{!collective.startsAt &&
console.warn(
`OrderForm: collective.startsAt should not be empty. collective.id: ${collective.id}`,
)}
{collective.startsAt && (
<React.Fragment>
<FormattedDate
value={collective.startsAt}
timeZone={collective.timezone}
weekday="short"
day="numeric"
month="long"
/>
,
<FormattedTime value={collective.startsAt} timeZone={collective.timezone} />
-
</React.Fragment>
)}
{get(collective, 'location.name')}
</div>
</Col>
</div>
</Col>
</Row>
</div>
)}
<Row>
<Col sm={12}>
<div className="form-group">
<label className="col-sm-2 control-label">
{order.tier.type !== 'TICKET' && (
<FormattedMessage id="tier.order.contribution" defaultMessage="Contribution" />
)}
{order.tier.type === 'TICKET' && (
<FormattedMessage id="tier.order.ticket" defaultMessage="Ticket" />
)}
</label>
<Col sm={10}>
<TierComponent
tier={order.tier}
values={{
quantity: order.tier.quantity || order.quantity, // TODO: confusing, need to fix
interval: order.interval || order.tier.interval,
amount: order.totalAmount,
}}
onChange={tier => this.handleChange('order', 'tier', tier)}
/>
</Col>
</div>
</Col>
</Row>
{this.props.matchingFund && (
<Row>
<Col sm={12}>
<MatchingFundWithData
collective={collective}
order={order}
uuid={this.props.matchingFund}
onChange={matchingFund => this.handleChange('order', 'matchingFund', matchingFund)}
/>
</Col>
</Row>
)}
<Row>
<Col sm={12}>
<InputField
label="Message (public)"
type="textarea"
name="publicMessage"
className="horizontal"
placeholder={intl.formatMessage(this.messages['order.publicMessage.placeholder'])}
defaultValue={order.publicMessage}
maxLength={255}
onChange={value => this.handleChange('order', 'publicMessage', value)}
/>
</Col>
</Row>
</section>
{order.totalAmount > 0 && (
<section className="paymentDetails">
<SectionTitle section="paymentDetails" />
{this.paymentMethodTypeOptions.length > 1 && (
<Row>
<Col sm={12}>
<InputField
className="horizontal"
type="select"
name="paymentMethodTypeSelector"
options={this.paymentMethodTypeOptions}
label={intl.formatMessage(this.messages['paymentMethod.type'])}
onChange={value => this.handleChange('paymentMethod', 'type', value)}
/>
</Col>
</Row>
)}
{this.state.paymentMethod.type === 'creditcard' && this.renderCreditCard()}
{this.state.paymentMethod.type === 'payment' && this.renderPayPalButton()}
{this.state.paymentMethod.type === 'manual' && (
<div className="horizontal form-group manualPaymentMethod ">
<label className="col-sm-2 control-label" />
<div
className="col-sm-10 instructions"
dangerouslySetInnerHTML={{
__html: intl.formatMessage(
{
id: 'host.paymentMethod.manual.instructions',
defaultMessage:
'Instructions to make the payment of {amount} will be sent to your email address {email}. Your order will be pending until the funds have been received by the host ({host}).',
},
{
amount: formatCurrency(order.totalAmount, order.tier.currency),
email: get(this.state, 'user.email', '') || get(LoggedInUser, 'email', ''),
collective: collective.slug,
host: get(collective, 'host.name'),
TierId: order.tier.id,
},
),
}}
/>
</div>
)}
</section>
)}
<Row key="summary-info">
<Col sm={2} />
<Col sm={10}>
{order.totalAmount > 0 && !collective.host && (
<div className="error">
<FormattedMessage
id="order.error.hostRequired"
defaultMessage="This collective doesn't have a host that can receive money on their behalf"
/>
</div>
)}
{(collective.host || order.totalAmount === 0) && !this.isPayPalSelected() && (
<div className="actions">
<div className="submit">
<ActionButton className="blue" onClick={this.handleSubmit} disabled={this.state.loading}>
{this.state.loading ? (
<FormattedMessage id="form.processing" defaultMessage="processing" />
) : (
order.tier.button || capitalize(intl.formatMessage(this.messages['order.button']))
)}
</ActionButton>
{this.state.loading && (
<div className="pleasewait">
<FormattedMessage id="pleasewait" defaultMessage="Please wait..." />
...
</div>
)}
</div>
{order.totalAmount > 0 &&
this.renderDisclaimer({
hostname: collective.host.name,
amount: formatCurrency(order.totalAmount, currency),
interval: order.interval || order.tier.interval,
collective: collective.name,
})}
<div className="result">
{this.state.result.success && <div className="success">{this.state.result.success}</div>}
{this.state.result.error && <div className="error">{this.state.result.error}</div>}
</div>
</div>
)}
</Col>
</Row>
</div>
)}
</Form>
</div>
);
}
}
export default withIntl(withApollo(OrderForm));
|
fields/types/geopoint/GeoPointColumn.js | helloworld3q3q/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var GeoPointColumn = React.createClass({
displayName: 'GeoPointColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
const formattedValue = `${value[1]}, ${value[0]}`;
const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`;
return (
<ItemsTableValue title={formattedTitle} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = GeoPointColumn;
|
project/Forms/js/jquery-1.5.2.min.js | tatikh/webdev | /*!
* jQuery JavaScript Library v1.5.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Mar 31 15:28:23 2011 -0400
*/
(function(a,b){function ci(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cf(a){if(!b_[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";b_[a]=c}return b_[a]}function ce(a,b){var c={};d.each(cd.concat.apply([],cd.slice(0,b)),function(){c[this]=a});return c}function b$(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bZ(){try{return new a.XMLHttpRequest}catch(b){}}function bY(){d(a).unload(function(){for(var a in bW)bW[a](0,1)})}function bS(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bR(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bQ(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bs.test(a)?e(a,f):bQ(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bQ(a+"["+f+"]",b[f],c,e)}function bP(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bJ,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bP(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bP(a,c,d,e,"*",g));return l}function bO(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bD),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bq(a,b,c){var e=b==="width"?bk:bl,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function bc(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function bb(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function ba(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function _(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function $(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Q(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(L.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function P(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function H(a,b){return(a&&a!=="*"?a+".":"")+b.replace(t,"`").replace(u,"&")}function G(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,p=[],q=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(r,"")===a.type?q.push(g.selector):t.splice(i--,1);f=d(a.target).closest(q,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){f=p[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function E(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function y(){return!0}function x(){return!1}function i(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function h(a,c,e){if(e===b&&a.nodeType===1){e=a.getAttribute("data-"+c);if(typeof e==="string"){try{e=e==="true"?!0:e==="false"?!1:e==="null"?null:d.isNaN(e)?g.test(e)?d.parseJSON(e):e:parseFloat(e)}catch(f){}d.data(a,c,e)}else e=b}return e}var c=a.document,d=function(){function G(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(G,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x,y,z=Object.prototype.toString,A=Object.prototype.hasOwnProperty,B=Array.prototype.push,C=Array.prototype.slice,D=String.prototype.trim,E=Array.prototype.indexOf,F={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.2",length:0,size:function(){return this.length},toArray:function(){return C.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?B.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),x.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(C.apply(this,arguments),"slice",C.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:B,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;x.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=d._Deferred();if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",y,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",y),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&G()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):F[z.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!A.call(a,"constructor")&&!A.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||A.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:D?function(a){return a==null?"":D.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?B.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){F["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),E&&(d.inArray=function(a,b){return E.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?y=function(){c.removeEventListener("DOMContentLoaded",y,!1),d.ready()}:c.attachEvent&&(y=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",y),d.ready())});return d}(),e="then done fail isResolved isRejected promise".split(" "),f=[].slice;d.extend({_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(d,f)}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),f;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(f)return f;f=a={}}var c=e.length;while(c--)a[e[c]]=b[e[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?f.call(arguments,0):c,--g||h.resolveWith(h,f.call(b,0))}}var b=arguments,c=0,e=b.length,g=e,h=e<=1&&a&&d.isFunction(a.promise)?a:d.Deferred();if(e>1){for(;c<e;c++)b[c]&&d.isFunction(b[c].promise)?b[c].promise().then(i(c),h.reject):--g;g||h.resolveWith(h,b)}else h!==a&&h.resolveWith(h,e?[a]:[]);return h.promise()}}),function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0,reliableMarginRight:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e)}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(a.style.width="1px",a.style.marginRight="0",d.support.reliableMarginRight=(parseInt(c.defaultView.getComputedStyle(a,null).marginRight,10)||0)===0),b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function");return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}}();var g=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!i(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,g=b.nodeType,h=g?d.cache:b,j=g?b[d.expando]:d.expando;if(!h[j])return;if(c){var k=e?h[j][f]:h[j];if(k){delete k[c];if(!i(k))return}}if(e){delete h[j][f];if(!i(h[j]))return}var l=h[j][f];d.support.deleteExpando||h!=a?delete h[j]:h[j]=null,l?(h[j]={},g||(h[j].toJSON=d.noop),h[j][f]=l):g&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var f=this[0].attributes,g;for(var i=0,j=f.length;i<j;i++)g=f[i].name,g.indexOf("data-")===0&&(g=g.substr(5),h(this[0],g,e[g]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=h(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var j=/[\n\t\r]/g,k=/\s+/,l=/\r/g,m=/^(?:href|src|style)$/,n=/^(?:button|input)$/i,o=/^(?:button|input|object|select|textarea)$/i,p=/^a(?:rea)?$/i,q=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(k);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(k);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(j," ");for(var i=0,l=c.length;i<l;i++)h=h.replace(" "+c[i]+" "," ");g.className=d.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),i=b,j=a.split(k);while(f=j[g++])i=e?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(j," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var j=i?f:0,k=i?f+1:h.length;j<k;j++){var m=h[j];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(q.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(l,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&q.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=m.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&n.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var k=a.getAttributeNode("tabIndex");return k&&k.specified?k.value:o.test(a.nodeName)||p.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var l=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return l===null?b:l}h&&(a[c]=e);return a[c]}});var r=/\.(.*)$/,s=/^(?:textarea|input|select)$/i,t=/\./g,u=/ /g,v=/[^\w\s.|`]/g,w=function(a){return a.replace(v,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=x;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(a){return typeof d!=="undefined"&&d.event.triggered!==a.type?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=x);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),w).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(r,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=a.type,l[m]())}catch(p){}k&&(l["on"+m]=k),d.event.triggered=b}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,H(a.origType,a.selector),d.extend({},a,{handler:G,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,H(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?y:x):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=y;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=y;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=y,this.stopPropagation()},isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x};var z=function(a){var b=a.relatedTarget;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},A=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?A:z,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?A:z)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&E("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&E("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var B,C=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},D=function D(a){var c=a.target,e,f;if(s.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=C(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:D,beforedeactivate:D,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&D.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&D.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",C(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in B)d.event.add(this,c+".specialChange",B[c]);return s.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return s.test(this.nodeName)}},B=d.event.special.change.filters,B.focus=B.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function f(a){var c=d.event.fix(a);c.type=b,c.originalEvent={},d.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var e=0;d.event.special[b]={setup:function(){e++===0&&c.addEventListener(a,f,!0)},teardown:function(){--e===0&&c.removeEventListener(a,f,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var F={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=r.exec(h),k="",j&&(k=j[0],h=h.replace(r,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(F[h]+k),h=h+k):h=(F[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)d.event.add(n[p],"live."+H(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+H(h,m),f)}return this}}),d.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".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return"text"===c&&(b===c||b===null)},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var I=/Until$/,J=/^(?:parents|prevUntil|prevAll)/,K=/,/,L=/^.[^:#\[\.,]*$/,M=Array.prototype.slice,N=d.expr.match.POS,O={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(Q(this,a,!1),"not",a)},filter:function(a){return this.pushStack(Q(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=N.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(P(c[0])||P(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=M.call(arguments);I.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!O[a]?d.unique(f):f,(this.length>1||K.test(e))&&J.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var R=/ jQuery\d+="(?:\d+|null)"/g,S=/^\s+/,T=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,U=/<([\w:]+)/,V=/<tbody/i,W=/<|&#?\w+;/,X=/<(?:script|object|embed|option|style)/i,Y=/checked\s*(?:[^=]|=\s*.checked.)/i,Z={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,"",""]};Z.optgroup=Z.option,Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,d.support.htmlSerialize||(Z._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(R,""):null;if(typeof a!=="string"||X.test(a)||!d.support.leadingWhitespace&&S.test(a)||Z[(U.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(T,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&Y.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?$(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,bc)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!X.test(a[0])&&(d.support.checkClone||!Y.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){ba(a,e),f=bb(a),g=bb(e);for(h=0;f[h];++h)ba(f[h],g[h])}if(b){_(a,e);if(c){f=bb(a),g=bb(e);for(h=0;f[h];++h)_(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||W.test(i)){if(typeof i==="string"){i=i.replace(T,"<$1></$2>");var j=(U.exec(i)||["",""])[1].toLowerCase(),k=Z[j]||Z._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=V.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&S.test(i)&&m.insertBefore(b.createTextNode(S.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bd=/alpha\([^)]*\)/i,be=/opacity=([^)]*)/,bf=/-([a-z])/ig,bg=/([A-Z]|^ms)/g,bh=/^-?\d+(?:px)?$/i,bi=/^-?\d/,bj={position:"absolute",visibility:"hidden",display:"block"},bk=["Left","Right"],bl=["Top","Bottom"],bm,bn,bo,bp=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bm(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bm)return bm(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bf,bp)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bq(a,b,e):d.swap(a,bj,function(){f=bq(a,b,e)});if(f<=0){f=bm(a,b,b),f==="0px"&&bo&&(f=bo(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bh.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return be.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bd.test(f)?f.replace(bd,e):c.filter+" "+e}}),d(function(){d.support.reliableMarginRight||(d.cssHooks.marginRight={get:function(a,b){var c;d.swap(a,{display:"inline-block"},function(){b?c=bm(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bn=function(a,c,e){var f,g,h;e=e.replace(bg,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bo=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bh.test(d)&&bi.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bm=bn||bo,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var br=/%20/g,bs=/\[\]$/,bt=/\r?\n/g,bu=/#.*$/,bv=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bw=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bx=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,by=/^(?:GET|HEAD)$/,bz=/^\/\//,bA=/\?/,bB=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bC=/^(?:select|textarea)/i,bD=/\s+/,bE=/([?&])_=[^&]*/,bF=/(^|\-)([a-z])/g,bG=function(a,b,c){return b+c.toUpperCase()},bH=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bI=d.fn.load,bJ={},bK={},bL,bM;try{bL=c.location.href}catch(bN){bL=c.createElement("a"),bL.href="",bL=bL.href}bM=bH.exec(bL.toLowerCase())||[],d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bI)return bI.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bB,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bC.test(this.nodeName)||bw.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(bt,"\r\n")}}):{name:b.name,value:c.replace(bt,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bL,isLocal:bx.test(bM[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bO(bJ),ajaxTransport:bO(bK),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bR(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bS(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bF,bG)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bv.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bu,"").replace(bz,bM[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bD),e.crossDomain==null&&(q=bH.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bM[1]||q[2]!=bM[2]||(q[3]||(q[1]==="http:"?80:443))!=(bM[3]||(bM[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bP(bJ,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!by.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(bA.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bE,"$1_="+w);e.url=x+(x===e.url?(bA.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bP(bK,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bQ(g,a[g],c,f);return e.join("&").replace(br,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bT=d.now(),bU=/(\=)\?(&|$)|\?\?/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bT++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bU.test(b.url)||f&&bU.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bU,l),b.url===j&&(f&&(k=k.replace(bU,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bV=d.now(),bW,bX;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bZ()||b$()}:bZ,bX=d.ajaxSettings.xhr(),d.support.ajax=!!bX,d.support.cors=bX&&"withCredentials"in bX,bX=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),!a.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bW[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bW||(bW={},bY()),h=bV++,g.onreadystatechange=bW[h]=c):c()},abort:function(){c&&c(0,1)}}}});var b_={},ca=/^(?:toggle|show|hide)$/,cb=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cc,cd=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(ce("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cf(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ce("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(ce("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cf(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(ca.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=cb.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:ce("show",1),slideUp:ce("hide",1),slideToggle:ce("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!cc&&(cc=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(cc),cc=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var cg=/^t(?:able|d|h)$/i,ch=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=ci(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!cg.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=(e==="absolute"||e==="fixed")&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=ch.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!ch.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=ci(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=ci(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window); |
docs/src/app/components/pages/components/Badge/ExampleSimple.js | rhaedes/material-ui | import React from 'react';
import Badge from 'material-ui/Badge';
import IconButton from 'material-ui/IconButton';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
const BadgeExampleSimple = () => (
<div>
<Badge
badgeContent={4}
primary={true}
>
<NotificationsIcon />
</Badge>
<Badge
badgeContent={10}
secondary={true}
badgeStyle={{top: 12, right: 12}}
>
<IconButton tooltip="Notifications">
<NotificationsIcon />
</IconButton>
</Badge>
</div>
);
export default BadgeExampleSimple;
|
src/components/PetitionImage/index.js | iris-dni/iris-frontend | import React from 'react';
import styles from './petition-image.scss';
import ImageContainer from 'components/ImageContainer';
import mapImageSizeToNewAttrs from 'helpers/mapImageSizeToNewAttrs';
const PetitionImage = ({ src, alt, attrs, ratio }) => (
src
? <div className={styles.root}>
<ImageContainer
src={src}
alt={alt}
attrs={mapImageSizeToNewAttrs(560, ratio)}
srcSet={[480, 560, 960, 1120]}
maxHeight={500}
sizes={'(min-width: 600px) 560px, 100vw'}
/>
</div>
: null
);
export default PetitionImage;
|
ajax/libs/formsy-react/0.7.1/formsy-react.min.js | Piicksarn/cdnjs | !function t(i,e,n){function s(o,u){if(!e[o]){if(!i[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var p=e[o]={exports:{}};i[o][0].call(p.exports,function(t){var e=i[o][1][t];return s(e?e:t)},p,p.exports,t,i,e,n)}return e[o].exports}for(var r="function"==typeof require&&require,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,i){(function(e){var n=e.React||t("react"),s={},r={isValue:function(t){return""!==t},isEmail:function(t){return t.match(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i)},isTrue:function(t){return t===!0},isNumeric:function(t){return"number"==typeof t?!0:t.match(/^-?[0-9]+$/)},isAlpha:function(t){return t.match(/^[a-zA-Z]+$/)},isWords:function(t){return t.match(/^[a-zA-Z\s]+$/)},isSpecialWords:function(t){return t.match(/^[a-zA-Z\s\u00C0-\u017F]+$/)},isLength:function(t,i,e){return void 0!==e?t.length>=i&&t.length<=e:t.length>=i},equals:function(t,i){return t==i},equalsField:function(t,i){return t===this[i]}},o=function(t,i,e){var e=e||[];if("object"==typeof t)for(var n in t)o(t[n],i?i+"["+n+"]":n,e);else e.push(i+"="+encodeURIComponent(t));return e.join("&")},u=function(t,i,e,n,s){var n="urlencoded"===n?"application/"+n.replace("urlencoded","x-www-form-urlencoded"):"application/json";return e="application/json"===n?JSON.stringify(e):o(e),new Promise(function(r,o){try{var u=new XMLHttpRequest;u.open(t,i,!0),u.setRequestHeader("Accept","application/json"),u.setRequestHeader("Content-Type",n),Object.keys(s).forEach(function(t){u.setRequestHeader(t,s[t])}),u.onreadystatechange=function(){if(4===u.readyState)try{var t=u.responseText?JSON.parse(u.responseText):null;u.status>=200&&u.status<300?r(t):o(t)}catch(i){o(i)}},u.send(e)}catch(a){o(a)}})},a=function(t,i){var e=!1;return t.length!==i.length?e=!0:t.forEach(function(t,n){t!==i[n]&&(e=!0)}),e},h={post:u.bind(null,"POST"),put:u.bind(null,"PUT")},p={};s.defaults=function(t){p=t},s.Mixin={getInitialState:function(){return{_value:this.props.value?this.props.value:"",_isValid:!0,_isPristine:!0}},componentWillMount:function(){var t=function(){this._validations=this.props.validations||"",this.props.required&&(this._validations=this.props.validations?this.props.validations+",":"",this._validations+="isValue"),this.props._attachToForm(this)}.bind(this);if(!this.props.name)throw new Error("Form Input requires a name property when used");return this.props._attachToForm?(t(),void 0):setTimeout(function(){if(!this.props._attachToForm)throw new Error("Form Mixin requires component to be nested in a Form");t()}.bind(this),0)},componentWillReceiveProps:function(t){t._attachToForm=this.props._attachToForm,t._detachFromForm=this.props._detachFromForm,t._validate=this.props._validate},componentDidUpdate:function(t){this.state._isPristine&&this.props.value!==t.value&&this.state._value===t.value&&(this.state._value=this.props.value||"",this.props._attachToForm(this))},componentWillUnmount:function(){this.props._detachFromForm(this)},setValue:function(t){this.setState({_value:t,_isPristine:!1},function(){this.props._validate(this)}.bind(this))},resetValue:function(){this.setState({_value:"",_isPristine:!0},function(){this.props._validate(this)})},getValue:function(){return this.state._value},hasValue:function(){return""!==this.state._value},getErrorMessage:function(){return this.isValid()||this.showRequired()?null:this.state._serverError||this.props.validationError},isValid:function(){return this.state._isValid},isPristine:function(){return this.state._isPristine},isRequired:function(){return!!this.props.required},showRequired:function(){return this.isRequired()&&""===this.state._value},showError:function(){return!this.showRequired()&&!this.state._isValid}},s.addValidationRule=function(t,i){r[t]=i},s.Form=n.createClass({displayName:"Form",getInitialState:function(){return{isValid:!0,isSubmitting:!1,canChange:!1}},getDefaultProps:function(){return{headers:{},onSuccess:function(){},onError:function(){},onSubmit:function(){},onSubmitted:function(){},onValid:function(){},onInvalid:function(){},onChange:function(){}}},componentWillMount:function(){this.inputs={},this.model={},this.registerInputs(this.props.children)},componentDidMount:function(){this.validateForm()},componentWillUpdate:function(){var t=Object.keys(this.inputs);setTimeout(function(){this.registerInputs(this.props.children);var i=Object.keys(this.inputs);a(t,i)&&this.validateForm()}.bind(this),0)},submit:function(t){if(t.preventDefault(),this.setFormPristine(!1),!this.props.url)return this.updateModel(),this.props.onSubmit(this.mapModel(),this.resetModel,this.updateInputsWithError),void 0;this.updateModel(),this.setState({isSubmitting:!0}),this.props.onSubmit(this.mapModel(),this.resetModel,this.updateInputsWithError);var i=Object.keys(this.props.headers).length&&this.props.headers||p.headers||{},e=this.props.method&&h[this.props.method.toLowerCase()]?this.props.method.toLowerCase():"post";h[e](this.props.url,this.mapModel(),this.props.contentType||p.contentType||"json",i).then(function(t){this.props.onSuccess(t),this.props.onSubmitted()}.bind(this)).catch(this.failSubmit)},mapModel:function(){return this.props.mapping?this.props.mapping(this.model):this.model},updateModel:function(){Object.keys(this.inputs).forEach(function(t){var i=this.inputs[t];this.model[t]=i.state._value}.bind(this))},resetModel:function(){Object.keys(this.inputs).forEach(function(t){this.inputs[t].resetValue()}.bind(this)),this.validateForm()},updateInputsWithError:function(t){Object.keys(t).forEach(function(i){var e=this.inputs[i];if(!e)throw new Error("You are trying to update an input that does not exists. Verify errors object with input names. "+JSON.stringify(t));var n=[{_isValid:!1,_serverError:t[i]}];e.setState.apply(e,n)}.bind(this))},failSubmit:function(t){this.updateInputsWithError(t),this.setState({isSubmitting:!1}),this.props.onError(t),this.props.onSubmitted()},registerInputs:function(t){n.Children.forEach(t,function(t){t&&t.props&&t.props.name&&(t.props._attachToForm=this.attachToForm,t.props._detachFromForm=this.detachFromForm,t.props._validate=this.validate),t&&t.props&&t.props.children&&this.registerInputs(t.props.children)}.bind(this))},getCurrentValues:function(){return Object.keys(this.inputs).reduce(function(t,i){var e=this.inputs[i];return t[i]=e.state._value,t}.bind(this),{})},setFormPristine:function(t){var i=this.inputs,e=Object.keys(i);e.forEach(function(e){var n=i[e];n.setState({_isPristine:t})}.bind(this))},validate:function(t){if(this.state.canChange&&this.props.onChange&&this.props.onChange(this.getCurrentValues()),t.props.required||t._validations){var i=this.runValidation(t);t.setState({_isValid:i,_serverError:null},this.validateForm)}},runValidation:function(t){var i=!0;return t._validations.length&&(t.props.required||""!==t.state._value)&&t._validations.split(",").forEach(function(e){var n=e.split(":"),s=n.shift();if(n=n.map(function(t){try{return JSON.parse(t)}catch(i){return t}}),n=[t.state._value].concat(n),!r[s])throw new Error("Formsy does not have the validation rule: "+s);r[s].apply(this.getCurrentValues(),n)||(i=!1)}.bind(this)),i},validateForm:function(){var t=!0,i=this.inputs,e=Object.keys(i),n=function(){e.forEach(function(e){i[e].state._isValid||(t=!1)}.bind(this)),this.setState({isValid:t}),t&&this.props.onValid(),!t&&this.props.onInvalid(),this.setState({canChange:!0})}.bind(this);e.forEach(function(t,s){var r=i[t],o=this.runValidation(r);r.setState({_isValid:o,_serverError:null},s===e.length-1?n:null)}.bind(this)),e.length||this.setState({canChange:!0})},attachToForm:function(t){this.inputs[t.props.name]=t,this.model[t.props.name]=t.state._value,this.validate(t)},detachFromForm:function(t){delete this.inputs[t.props.name],delete this.model[t.props.name]},render:function(){return n.DOM.form({onSubmit:this.submit,className:this.props.className},this.props.children)}}),e.exports||e.module||e.define&&e.define.amd||(e.Formsy=s),i.exports=s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{react:"react"}]},{},[1]); |
src/packages/@ncigdc/components/analysis/SetOperations/OpsTable.js | NCI-GDC/portal-ui | import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'recompose';
import urlJoin from 'url-join';
import { AUTH_API, MAX_SET_SIZE } from '@ncigdc/utils/constants';
import Table, {
Tr, Td, TdNum, ThNum,
} from '@ncigdc/uikit/Table';
import { stringifyJSONParam } from '@ncigdc/utils/uri';
import { Tooltip } from '@ncigdc/uikit/Tooltip';
import { setModal } from '@ncigdc/dux/modal';
import SaveSetModal from '@ncigdc/components/Modals/SaveSetModal';
import GreyBox from '@ncigdc/uikit/GreyBox';
import { withTheme } from '@ncigdc/theme';
import download from '@ncigdc/utils/download';
import DownloadIcon from '@ncigdc/theme/icons/Download';
import timestamp from '@ncigdc/utils/timestamp';
const ActionsTd = compose(
connect(),
withTheme,
)(
({
count,
CreateSetButton,
dispatch,
fileName,
filters,
hide,
push,
theme,
type,
}) => {
const saveSetDisabled = count > MAX_SET_SIZE;
return (
<Td style={{ textAlign: 'right' }}>
{!hide && (
<span>
<Tooltip
Component={
saveSetDisabled
? `Set Operation can not be saved because it is over the limit of ${MAX_SET_SIZE}`
: 'Save selection as new set'
}
style={{ marginRight: 5 }}
>
<i
className="fa fa-save"
onClick={() => {
if (saveSetDisabled) return;
dispatch(
setModal(
<SaveSetModal
CreateSetButton={CreateSetButton}
displayType={type}
filters={filters}
setName="My Set"
title="Save selection as new set"
total={count}
type={type}
/>,
),
);
}}
style={
saveSetDisabled
? { color: theme.greyScale4 }
: {
cursor: 'pointer',
color: 'rgb(37, 94, 153)',
}
}
/>
</Tooltip>
<CreateSetButton
Component={props => (
<Tooltip
{...props}
Component="Export as TSV"
style={{
cursor: 'pointer',
color: theme.primary,
textDecoration: 'underline',
}}
>
<DownloadIcon key="icon" style={{ marginRight: '5px' }} />
</Tooltip>
)}
filters={filters}
onComplete={setId => {
download({
params: {
attachment: true,
format: 'tsv',
sets: [
{
id: setId,
type,
filename: `${fileName
.replace(/∩/g, 'intersection')
.replace(/∪/g, 'union')}.tsv`,
},
],
},
url: urlJoin(AUTH_API, '/tar_sets'),
method: 'POST',
altMessage: false,
})(() => {}, () => {});
}}
/>
{type === 'case' && (
<CreateSetButton
Component={p => (
<Tooltip Component="View files in repository">
<i
className="fa fa-database"
{...p}
style={{
cursor: 'pointer',
color: 'rgb(37, 94, 153)',
}}
/>
</Tooltip>
)}
filters={filters}
onComplete={setId => {
push({
pathname: '/repository',
query: {
filters: stringifyJSONParam({
op: 'AND',
content: [
{
op: 'IN',
content: {
field: `${type}s.${type}_id`,
value: [`set_id:${setId}`],
},
},
],
}),
},
});
}}
/>
)}
</span>
)}
</Td>
);
},
);
export default compose(
withTheme,
)(
({
CountComponent,
CreateSetButton,
ops,
push,
selected,
selectedFilters,
theme,
toggle,
type,
}) => (
<Table
body={(
<tbody>
{ops.map((op, i) => (
<CountComponent filters={op.filters} key={op.op}>
{count => (
<Tr
index={i}
style={{
...(selected.has(op.op) && {
backgroundColor: theme.tableHighlight,
}),
}}
>
<Td>
<input
aria-label={`Select ${op.op}`}
checked={selected.has(op.op)}
onChange={e => toggle(op.op)}
type="checkbox"
/>
</Td>
<Td>{op.op}</Td>
<TdNum>
{count === 0 ? (
0
) : count === '' ? (
<GreyBox />
) : (
<CreateSetButton
Component={props => (
<Tooltip
{...props}
Component={`View ${type} set in exploration`}
style={{
cursor: 'pointer',
color: theme.primary,
textDecoration: 'underline',
}}
>
{count.toLocaleString()}
</Tooltip>
)}
filters={op.filters}
onComplete={setId => {
push({
pathname: '/exploration',
query: {
searchTableTab:
`${type === 'ssm' ? 'mutation' : type}s`,
filters: stringifyJSONParam({
op: 'AND',
content: [
{
op: 'IN',
content: {
field: `${type}s.${type}_id`,
value: [`set_id:${setId}`],
},
},
],
}),
},
});
}}
/>
)}
</TdNum>
<ActionsTd
count={count}
CreateSetButton={CreateSetButton}
fileName={`${op.op}-set-ids.${timestamp()}.json`}
filters={op.filters}
hide={!count}
push={push}
type={type}
/>
</Tr>
)}
</CountComponent>
))}
<CountComponent filters={selectedFilters}>
{count => (
<Tr
style={{
borderTop: '1px solid black',
borderBottom: '1px solid black',
}}
>
<Td colSpan="2">
<b>Union of selected sets</b>
</Td>
<TdNum>
{selected.size === 0 || count === 0 ? (
0
) : count === '' ? (
<GreyBox />
) : (
<CreateSetButton
Component={p => (
<Tooltip Component={`View ${type} set in exploration`}>
<span
{...p}
style={{
cursor: 'pointer',
color: theme.primary,
textDecoration: 'underline',
}}
>
{count.toLocaleString()}
</span>
</Tooltip>
)}
filters={selectedFilters}
onComplete={setId => {
push({
pathname: '/exploration',
query: {
searchTableTab:
`${type === 'ssm' ? 'mutation' : type}s`,
filters: stringifyJSONParam({
op: 'AND',
content: [
{
op: 'IN',
content: {
field: `${type}s.${type}_id`,
value: [`set_id:${setId}`],
},
},
],
}),
},
});
}}
/>
)}
</TdNum>
<ActionsTd
count={count}
CreateSetButton={CreateSetButton}
fileName={`union-of-set-ids.${timestamp()}.json`}
filters={selectedFilters}
hide={!selected.size || !count}
push={push}
type={type}
/>
</Tr>
)}
</CountComponent>
</tbody>
)}
headings={[
'Select',
'Set Operation',
<ThNum key="# Items"># Items</ThNum>,
'Save',
]}
/>
),
);
|
packages/material-ui-icons/src/FilterHdr.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let FilterHdr = props =>
<SvgIcon {...props}>
<path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z" />
</SvgIcon>;
FilterHdr = pure(FilterHdr);
FilterHdr.muiName = 'SvgIcon';
export default FilterHdr;
|
src/index.js | oguennec/react-native-redux-todos | import React, { Component } from 'react';
import { createStore, applyMiddleware } from 'redux';
import { connect, Provider } from 'react-redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import App from './components/App';
import reducer from './reducers';
import { getTodos } from './actions';
const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
const store = createStore(
reducer,
applyMiddleware(...middleware)
);
store.dispatch(getTodos());
const AppWrapper = () => {
return (
<Provider store={store}>
<App />
</Provider>
);
};
export default AppWrapper;
|
ajax/libs/parsley.js/2.4.2/parsley.js | joeyparrish/cdnjs | /*!
* Parsley.js
* Version 2.4.2 - built Wed, Jun 15th 2016, 9:15 am
* http://parsleyjs.org
* Guillaume Potier - <guillaume@wisembly.com>
* Marc-Andre Lafortune - <petroselinum@marc-andre.ca>
* MIT Licensed
*/
// The source code below is generated by babel as
// Parsley is written in ECMAScript 6
//
var _slice = Array.prototype.slice;
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); } }
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : global.parsley = factory(global.jQuery);
})(this, function ($) {
'use strict';
var globalID = 1;
var pastWarnings = {};
var ParsleyUtils__ParsleyUtils = {
// Parsley DOM-API
// returns object from dom attributes and values
attr: function attr($element, namespace, obj) {
var i;
var attribute;
var attributes;
var regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof obj) obj = {};else {
// Clear all own properties. This won't affect prototype's values
for (i in obj) {
if (obj.hasOwnProperty(i)) delete obj[i];
}
}
if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return obj;
attributes = $element[0].attributes;
for (i = attributes.length; i--;) {
attribute = attributes[i];
if (attribute && attribute.specified && regex.test(attribute.name)) {
obj[this.camelize(attribute.name.slice(namespace.length))] = this.deserializeValue(attribute.value);
}
}
return obj;
},
checkAttr: function checkAttr($element, namespace, _checkAttr) {
return $element.is('[' + namespace + _checkAttr + ']');
},
setAttr: function setAttr($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
generateID: function generateID() {
return '' + globalID++;
},
/** Third party functions **/
// Zepto deserialize function
deserializeValue: function deserializeValue(value) {
var num;
try {
return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value;
} catch (e) {
return value;
}
},
// Zepto camelize function
camelize: function camelize(str) {
return str.replace(/-+(.)?/g, function (match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function dasherize(str) {
return str.replace(/::/g, '/').replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/_/g, '-').toLowerCase();
},
warn: function warn() {
var _window$console;
if (window.console && 'function' === typeof window.console.warn) (_window$console = window.console).warn.apply(_window$console, arguments);
},
warnOnce: function warnOnce(msg) {
if (!pastWarnings[msg]) {
pastWarnings[msg] = true;
this.warn.apply(this, arguments);
}
},
_resetWarnings: function _resetWarnings() {
pastWarnings = {};
},
trimString: function trimString(string) {
return string.replace(/^\s+|\s+$/g, '');
},
namespaceEvents: function namespaceEvents(events, namespace) {
events = this.trimString(events || '').split(/\s+/);
if (!events[0]) return '';
return $.map(events, function (evt) {
return evt + '.' + namespace;
}).join(' ');
},
difference: function difference(array, remove) {
// This is O(N^2), should be optimized
var result = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var elem = _step.value;
if (remove.indexOf(elem) == -1) result.push(elem);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return result;
},
// Alter-ego to native Promise.all, but for jQuery
all: function all(promises) {
// jQuery treats $.when() and $.when(singlePromise) differently; let's avoid that and add spurious elements
return $.when.apply($, _toConsumableArray(promises).concat([42, 42]));
},
// Object.create polyfill, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
objectCreate: Object.create || (function () {
var Object = function Object() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}
Object.prototype = prototype;
var result = new Object();
Object.prototype = null;
return result;
};
})()
};
var ParsleyUtils__default = ParsleyUtils__ParsleyUtils;
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
var ParsleyDefaults = {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### Field only
// identifier used to group together inputs (e.g. radio buttons...)
multiple: null,
// identifier (or array of identifiers) used to validate only a select group of inputs
group: null,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'first'|'last'|'none'
focus: 'first',
// event(s) that will trigger validation before first failure. eg: `input`...
trigger: false,
// event(s) that will trigger validation after first failure.
triggerAfterFailure: 'input',
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function classHandler(ParsleyField) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function errorsContainer(ParsleyField) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
var ParsleyAbstract = function ParsleyAbstract() {
this.__id__ = ParsleyUtils__default.generateID();
};
ParsleyAbstract.prototype = {
asyncSupport: true, // Deprecated
_pipeAccordingToValidationResult: function _pipeAccordingToValidationResult() {
var _this = this;
var pipe = function pipe() {
var r = $.Deferred();
if (true !== _this.validationResult) r.reject();
return r.resolve().promise();
};
return [pipe, pipe];
},
actualizeOptions: function actualizeOptions() {
ParsleyUtils__default.attr(this.$element, this.options.namespace, this.domOptions);
if (this.parent && this.parent.actualizeOptions) this.parent.actualizeOptions();
return this;
},
_resetOptions: function _resetOptions(initOptions) {
this.domOptions = ParsleyUtils__default.objectCreate(this.parent.options);
this.options = ParsleyUtils__default.objectCreate(this.domOptions);
// Shallow copy of ownProperties of initOptions:
for (var i in initOptions) {
if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i];
}
this.actualizeOptions();
},
_listeners: null,
// Register a callback for the given event name
// Callback is called with context as the first argument and the `this`
// The context is the current parsley instance, or window.Parsley if global
// A return value of `false` will interrupt the calls
on: function on(name, fn) {
this._listeners = this._listeners || {};
var queue = this._listeners[name] = this._listeners[name] || [];
queue.push(fn);
return this;
},
// Deprecated. Use `on` instead
subscribe: function subscribe(name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
},
// Unregister a callback (or all if none is given) for the given event name
off: function off(name, fn) {
var queue = this._listeners && this._listeners[name];
if (queue) {
if (!fn) {
delete this._listeners[name];
} else {
for (var i = queue.length; i--;) if (queue[i] === fn) queue.splice(i, 1);
}
}
return this;
},
// Deprecated. Use `off`
unsubscribe: function unsubscribe(name, fn) {
$.unsubscribeTo(this, name.toLowerCase());
},
// Trigger an event of the given name
// A return value of `false` interrupts the callback chain
// Returns false if execution was interrupted
trigger: function trigger(name, target, extraArg) {
target = target || this;
var queue = this._listeners && this._listeners[name];
var result;
var parentResult;
if (queue) {
for (var i = queue.length; i--;) {
result = queue[i].call(target, target, extraArg);
if (result === false) return result;
}
}
if (this.parent) {
return this.parent.trigger(name, target, extraArg);
}
return true;
},
// Reset UI
reset: function reset() {
// Field case: just emit a reset event for UI
if ('ParsleyForm' !== this.__class__) {
this._resetUI();
return this._trigger('reset');
}
// Form case: emit a reset event for each field
for (var i = 0; i < this.fields.length; i++) this.fields[i].reset();
this._trigger('reset');
},
// Destroy Parsley instance (+ UI)
destroy: function destroy() {
// Field case: emit destroy event to clean UI and then destroy stored instance
this._destroyUI();
if ('ParsleyForm' !== this.__class__) {
this.$element.removeData('Parsley');
this.$element.removeData('ParsleyFieldMultiple');
this._trigger('destroy');
return;
}
// Form case: destroy all its fields and then destroy stored instance
for (var i = 0; i < this.fields.length; i++) this.fields[i].destroy();
this.$element.removeData('Parsley');
this._trigger('destroy');
},
asyncIsValid: function asyncIsValid(group, force) {
ParsleyUtils__default.warnOnce("asyncIsValid is deprecated; please use whenValid instead");
return this.whenValid({ group: group, force: force });
},
_findRelated: function _findRelated() {
return this.options.multiple ? this.parent.$element.find('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]') : this.$element;
}
};
var requirementConverters = {
string: function string(_string) {
return _string;
},
integer: function integer(string) {
if (isNaN(string)) throw 'Requirement is not an integer: "' + string + '"';
return parseInt(string, 10);
},
number: function number(string) {
if (isNaN(string)) throw 'Requirement is not a number: "' + string + '"';
return parseFloat(string);
},
reference: function reference(string) {
// Unused for now
var result = $(string);
if (result.length === 0) throw 'No such reference: "' + string + '"';
return result;
},
boolean: function boolean(string) {
return string !== 'false';
},
object: function object(string) {
return ParsleyUtils__default.deserializeValue(string);
},
regexp: function regexp(_regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (/^\/.*\/(?:[gimy]*)$/.test(_regexp)) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = _regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
_regexp = _regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
} else {
// Anchor regexp:
_regexp = '^' + _regexp + '$';
}
return new RegExp(_regexp, flags);
}
};
var convertArrayRequirement = function convertArrayRequirement(string, length) {
var m = string.match(/^\s*\[(.*)\]\s*$/);
if (!m) throw 'Requirement is not an array: "' + string + '"';
var values = m[1].split(',').map(ParsleyUtils__default.trimString);
if (values.length !== length) throw 'Requirement has ' + values.length + ' values when ' + length + ' are needed';
return values;
};
var convertRequirement = function convertRequirement(requirementType, string) {
var converter = requirementConverters[requirementType || 'string'];
if (!converter) throw 'Unknown requirement specification: "' + requirementType + '"';
return converter(string);
};
var convertExtraOptionRequirement = function convertExtraOptionRequirement(requirementSpec, string, extraOptionReader) {
var main = null;
var extra = {};
for (var key in requirementSpec) {
if (key) {
var value = extraOptionReader(key);
if ('string' === typeof value) value = convertRequirement(requirementSpec[key], value);
extra[key] = value;
} else {
main = convertRequirement(requirementSpec[key], string);
}
}
return [main, extra];
};
// A Validator needs to implement the methods `validate` and `parseRequirements`
var ParsleyValidator = function ParsleyValidator(spec) {
$.extend(true, this, spec);
};
ParsleyValidator.prototype = {
// Returns `true` iff the given `value` is valid according the given requirements.
validate: function validate(value, requirementFirstArg) {
if (this.fn) {
// Legacy style validator
if (arguments.length > 3) // If more args then value, requirement, instance...
requirementFirstArg = [].slice.call(arguments, 1, -1); // Skip first arg (value) and last (instance), combining the rest
return this.fn.call(this, value, requirementFirstArg);
}
if ($.isArray(value)) {
if (!this.validateMultiple) throw 'Validator `' + this.name + '` does not handle multiple values';
return this.validateMultiple.apply(this, arguments);
} else {
if (this.validateNumber) {
if (isNaN(value)) return false;
arguments[0] = parseFloat(arguments[0]);
return this.validateNumber.apply(this, arguments);
}
if (this.validateString) {
return this.validateString.apply(this, arguments);
}
throw 'Validator `' + this.name + '` only handles multiple values';
}
},
// Parses `requirements` into an array of arguments,
// according to `this.requirementType`
parseRequirements: function parseRequirements(requirements, extraOptionReader) {
if ('string' !== typeof requirements) {
// Assume requirement already parsed
// but make sure we return an array
return $.isArray(requirements) ? requirements : [requirements];
}
var type = this.requirementType;
if ($.isArray(type)) {
var values = convertArrayRequirement(requirements, type.length);
for (var i = 0; i < values.length; i++) values[i] = convertRequirement(type[i], values[i]);
return values;
} else if ($.isPlainObject(type)) {
return convertExtraOptionRequirement(type, requirements, extraOptionReader);
} else {
return [convertRequirement(type, requirements)];
}
},
// Defaults:
requirementType: 'string',
priority: 2
};
var ParsleyValidatorRegistry = function ParsleyValidatorRegistry(validators, catalog) {
this.__class__ = 'ParsleyValidatorRegistry';
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
var typeRegexes = {
email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
// Follow https://www.w3.org/TR/html5/infrastructure.html#floating-point-numbers
number: /^-?(\d*\.)?\d+(e[-+]?\d+)?$/i,
integer: /^-?\d+$/,
digits: /^\d+$/,
alphanum: /^\w+$/i,
url: new RegExp("^" +
// protocol identifier
"(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" + "(?:" +
// IP address exclusion
// private & local networks
// "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks
// "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
// TLD identifier
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' + ")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:/\\S*)?" + "$", 'i')
};
typeRegexes.range = typeRegexes.number;
// See http://stackoverflow.com/a/10454560/8279
var decimalPlaces = function decimalPlaces(num) {
var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) {
return 0;
}
return Math.max(0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0) - (
// Adjust for scientific notation.
match[2] ? +match[2] : 0));
};
ParsleyValidatorRegistry.prototype = {
init: function init(validators, catalog) {
this.catalog = catalog;
// Copy prototype's validators:
this.validators = $.extend({}, this.validators);
for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority);
window.Parsley.trigger('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function setLocale(locale) {
if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function addCatalog(locale, messages, set) {
if ('object' === typeof messages) this.catalog[locale] = messages;
if (true === set) return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function addMessage(locale, name, message) {
if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {};
this.catalog[locale][name] = message;
return this;
},
// Add messages for a given locale
addMessages: function addMessages(locale, nameMessageObject) {
for (var name in nameMessageObject) this.addMessage(locale, name, nameMessageObject[name]);
return this;
},
// Add a new validator
//
// addValidator('custom', {
// requirementType: ['integer', 'integer'],
// validateString: function(value, from, to) {},
// priority: 22,
// messages: {
// en: "Hey, that's no good",
// fr: "Aye aye, pas bon du tout",
// }
// })
//
// Old API was addValidator(name, function, priority)
//
addValidator: function addValidator(name, arg1, arg2) {
if (this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is already defined.');else if (ParsleyDefaults.hasOwnProperty(name)) {
ParsleyUtils__default.warn('"' + name + '" is a restricted keyword and is not a valid validator name.');
return;
}
return this._setValidator.apply(this, arguments);
},
updateValidator: function updateValidator(name, arg1, arg2) {
if (!this.validators[name]) {
ParsleyUtils__default.warn('Validator "' + name + '" is not already defined.');
return this.addValidator.apply(this, arguments);
}
return this._setValidator.apply(this, arguments);
},
removeValidator: function removeValidator(name) {
if (!this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is not defined.');
delete this.validators[name];
return this;
},
_setValidator: function _setValidator(name, validator, priority) {
if ('object' !== typeof validator) {
// Old style validator, with `fn` and `priority`
validator = {
fn: validator,
priority: priority
};
}
if (!validator.validate) {
validator = new ParsleyValidator(validator);
}
this.validators[name] = validator;
for (var locale in validator.messages || {}) this.addMessage(locale, name, validator.messages[locale]);
return this;
},
getErrorMessage: function getErrorMessage(constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name) {
var typeMessages = this.catalog[this.locale][constraint.name] || {};
message = typeMessages[constraint.requirements];
} else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMessage: function formatMessage(string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters) string = this.formatMessage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(/%s/i, parameters) : '';
},
// Here is the Parsley default validators list.
// A validator is an object with the following key values:
// - priority: an integer
// - requirement: 'string' (default), 'integer', 'number', 'regexp' or an Array of these
// - validateString, validateMultiple, validateNumber: functions returning `true`, `false` or a promise
// Alternatively, a validator can be a function that returns such an object
//
validators: {
notblank: {
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 2
},
required: {
validateMultiple: function validateMultiple(values) {
return values.length > 0;
},
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 512
},
type: {
validateString: function validateString(value, type) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$step = _ref.step;
var step = _ref$step === undefined ? '1' : _ref$step;
var _ref$base = _ref.base;
var base = _ref$base === undefined ? 0 : _ref$base;
var regex = typeRegexes[type];
if (!regex) {
throw new Error('validator type `' + type + '` is not supported');
}
if (!regex.test(value)) return false;
if ('number' === type) {
if (!/^any$/i.test(step || '')) {
var nb = Number(value);
var decimals = Math.max(decimalPlaces(step), decimalPlaces(base));
if (decimalPlaces(nb) > decimals) // Value can't have too many decimals
return false;
// Be careful of rounding errors by using integers.
var toInt = function toInt(f) {
return Math.round(f * Math.pow(10, decimals));
};
if ((toInt(nb) - toInt(base)) % toInt(step) != 0) return false;
}
}
return true;
},
requirementType: {
'': 'string',
step: 'string',
base: 'number'
},
priority: 256
},
pattern: {
validateString: function validateString(value, regexp) {
return regexp.test(value);
},
requirementType: 'regexp',
priority: 64
},
minlength: {
validateString: function validateString(value, requirement) {
return value.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxlength: {
validateString: function validateString(value, requirement) {
return value.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
length: {
validateString: function validateString(value, min, max) {
return value.length >= min && value.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
mincheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxcheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
check: {
validateMultiple: function validateMultiple(values, min, max) {
return values.length >= min && values.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
min: {
validateNumber: function validateNumber(value, requirement) {
return value >= requirement;
},
requirementType: 'number',
priority: 30
},
max: {
validateNumber: function validateNumber(value, requirement) {
return value <= requirement;
},
requirementType: 'number',
priority: 30
},
range: {
validateNumber: function validateNumber(value, min, max) {
return value >= min && value <= max;
},
requirementType: ['number', 'number'],
priority: 30
},
equalto: {
validateString: function validateString(value, refOrValue) {
var $reference = $(refOrValue);
if ($reference.length) return value === $reference.val();else return value === refOrValue;
},
priority: 256
}
}
};
var ParsleyUI = {};
var diffResults = function diffResults(newResult, oldResult, deep) {
var added = [];
var kept = [];
for (var i = 0; i < newResult.length; i++) {
var found = false;
for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) {
found = true;
break;
}
if (found) kept.push(newResult[i]);else added.push(newResult[i]);
}
return {
kept: kept,
added: added,
removed: !deep ? diffResults(oldResult, newResult, true).added : []
};
};
ParsleyUI.Form = {
_actualizeTriggers: function _actualizeTriggers() {
var _this2 = this;
this.$element.on('submit.Parsley', function (evt) {
_this2.onSubmitValidate(evt);
});
this.$element.on('click.Parsley', 'input[type="submit"], button[type="submit"]', function (evt) {
_this2.onSubmitButton(evt);
});
// UI could be disabled
if (false === this.options.uiEnabled) return;
this.$element.attr('novalidate', '');
},
focus: function focus() {
this._focusedField = null;
if (true === this.validationResult || 'none' === this.options.focus) return null;
for (var i = 0; i < this.fields.length; i++) {
var field = this.fields[i];
if (true !== field.validationResult && field.validationResult.length > 0 && 'undefined' === typeof field.options.noFocus) {
this._focusedField = field.$element;
if ('first' === this.options.focus) break;
}
}
if (null === this._focusedField) return null;
return this._focusedField.focus();
},
_destroyUI: function _destroyUI() {
// Reset all event listeners
this.$element.off('.Parsley');
}
};
ParsleyUI.Field = {
_reflowUI: function _reflowUI() {
this._buildUI();
// If this field doesn't have an active UI don't bother doing something
if (!this._ui) return;
// Diff between two validation results
var diff = diffResults(this.validationResult, this._ui.lastValidationResult);
// Then store current validation result for next reflow
this._ui.lastValidationResult = this.validationResult;
// Handle valid / invalid / none field class
this._manageStatusClass();
// Add, remove, updated errors messages
this._manageErrorsMessages(diff);
// Triggers impl
this._actualizeTriggers();
// If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user
if ((diff.kept.length || diff.added.length) && !this._failedOnce) {
this._failedOnce = true;
this._actualizeTriggers();
}
},
// Returns an array of field's error message(s)
getErrorsMessages: function getErrorsMessages() {
// No error message, field is valid
if (true === this.validationResult) return [];
var messages = [];
for (var i = 0; i < this.validationResult.length; i++) messages.push(this.validationResult[i].errorMessage || this._getErrorMessage(this.validationResult[i].assert));
return messages;
},
// It's a goal of Parsley that this method is no longer required [#1073]
addError: function addError(name) {
var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref2.message;
var assert = _ref2.assert;
var _ref2$updateClass = _ref2.updateClass;
var updateClass = _ref2$updateClass === undefined ? true : _ref2$updateClass;
this._buildUI();
this._addError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
updateError: function updateError(name) {
var _ref3 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref3.message;
var assert = _ref3.assert;
var _ref3$updateClass = _ref3.updateClass;
var updateClass = _ref3$updateClass === undefined ? true : _ref3$updateClass;
this._buildUI();
this._updateError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
removeError: function removeError(name) {
var _ref4 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref4$updateClass = _ref4.updateClass;
var updateClass = _ref4$updateClass === undefined ? true : _ref4$updateClass;
this._buildUI();
this._removeError(name);
// edge case possible here: remove a standard Parsley error that is still failing in this.validationResult
// but highly improbable cuz' manually removing a well Parsley handled error makes no sense.
if (updateClass) this._manageStatusClass();
},
_manageStatusClass: function _manageStatusClass() {
if (this.hasConstraints() && this.needsValidation() && true === this.validationResult) this._successClass();else if (this.validationResult.length > 0) this._errorClass();else this._resetClass();
},
_manageErrorsMessages: function _manageErrorsMessages(diff) {
if ('undefined' !== typeof this.options.errorsMessagesDisabled) return;
// Case where we have errorMessage option that configure an unique field error message, regardless failing validators
if ('undefined' !== typeof this.options.errorMessage) {
if (diff.added.length || diff.kept.length) {
this._insertErrorWrapper();
if (0 === this._ui.$errorsWrapper.find('.parsley-custom-error-message').length) this._ui.$errorsWrapper.append($(this.options.errorTemplate).addClass('parsley-custom-error-message'));
return this._ui.$errorsWrapper.addClass('filled').find('.parsley-custom-error-message').html(this.options.errorMessage);
}
return this._ui.$errorsWrapper.removeClass('filled').find('.parsley-custom-error-message').remove();
}
// Show, hide, update failing constraints messages
for (var i = 0; i < diff.removed.length; i++) this._removeError(diff.removed[i].assert.name);
for (i = 0; i < diff.added.length; i++) this._addError(diff.added[i].assert.name, { message: diff.added[i].errorMessage, assert: diff.added[i].assert });
for (i = 0; i < diff.kept.length; i++) this._updateError(diff.kept[i].assert.name, { message: diff.kept[i].errorMessage, assert: diff.kept[i].assert });
},
_addError: function _addError(name, _ref5) {
var message = _ref5.message;
var assert = _ref5.assert;
this._insertErrorWrapper();
this._ui.$errorsWrapper.addClass('filled').append($(this.options.errorTemplate).addClass('parsley-' + name).html(message || this._getErrorMessage(assert)));
},
_updateError: function _updateError(name, _ref6) {
var message = _ref6.message;
var assert = _ref6.assert;
this._ui.$errorsWrapper.addClass('filled').find('.parsley-' + name).html(message || this._getErrorMessage(assert));
},
_removeError: function _removeError(name) {
this._ui.$errorsWrapper.removeClass('filled').find('.parsley-' + name).remove();
},
_getErrorMessage: function _getErrorMessage(constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof this.options[customConstraintErrorMessage]) return window.Parsley.formatMessage(this.options[customConstraintErrorMessage], constraint.requirements);
return window.Parsley.getErrorMessage(constraint);
},
_buildUI: function _buildUI() {
// UI could be already built or disabled
if (this._ui || false === this.options.uiEnabled) return;
var _ui = {};
// Give field its Parsley id in DOM
this.$element.attr(this.options.namespace + 'id', this.__id__);
/** Generate important UI elements and store them in this **/
// $errorClassHandler is the $element that woul have parsley-error and parsley-success classes
_ui.$errorClassHandler = this._manageClassHandler();
// $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer
_ui.errorsWrapperId = 'parsley-id-' + (this.options.multiple ? 'multiple-' + this.options.multiple : this.__id__);
_ui.$errorsWrapper = $(this.options.errorsWrapper).attr('id', _ui.errorsWrapperId);
// ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly
_ui.lastValidationResult = [];
_ui.validationInformationVisible = false;
// Store it in this for later
this._ui = _ui;
},
// Determine which element will have `parsley-error` and `parsley-success` classes
_manageClassHandler: function _manageClassHandler() {
// An element selector could be passed through DOM with `data-parsley-class-handler=#foo`
if ('string' === typeof this.options.classHandler && $(this.options.classHandler).length) return $(this.options.classHandler);
// Class handled could also be determined by function given in Parsley options
var $handler = this.options.classHandler.call(this, this);
// If this function returned a valid existing DOM element, go for it
if ('undefined' !== typeof $handler && $handler.length) return $handler;
// Otherwise, if simple element (input, texatrea, select...) it will perfectly host the classes
if (!this.options.multiple || this.$element.is('select')) return this.$element;
// But if multiple element (radio, checkbox), that would be their parent
return this.$element.parent();
},
_insertErrorWrapper: function _insertErrorWrapper() {
var $errorsContainer;
// Nothing to do if already inserted
if (0 !== this._ui.$errorsWrapper.parent().length) return this._ui.$errorsWrapper.parent();
if ('string' === typeof this.options.errorsContainer) {
if ($(this.options.errorsContainer).length) return $(this.options.errorsContainer).append(this._ui.$errorsWrapper);else ParsleyUtils__default.warn('The errors container `' + this.options.errorsContainer + '` does not exist in DOM');
} else if ('function' === typeof this.options.errorsContainer) $errorsContainer = this.options.errorsContainer.call(this, this);
if ('undefined' !== typeof $errorsContainer && $errorsContainer.length) return $errorsContainer.append(this._ui.$errorsWrapper);
var $from = this.$element;
if (this.options.multiple) $from = $from.parent();
return $from.after(this._ui.$errorsWrapper);
},
_actualizeTriggers: function _actualizeTriggers() {
var _this3 = this;
var $toBind = this._findRelated();
var trigger;
// Remove Parsley events already bound on this field
$toBind.off('.Parsley');
if (this._failedOnce) $toBind.on(ParsleyUtils__default.namespaceEvents(this.options.triggerAfterFailure, 'Parsley'), function () {
_this3.validate();
});else if (trigger = ParsleyUtils__default.namespaceEvents(this.options.trigger, 'Parsley')) {
$toBind.on(trigger, function (event) {
_this3._eventValidate(event);
});
}
},
_eventValidate: function _eventValidate(event) {
// For keyup, keypress, keydown, input... events that could be a little bit obstrusive
// do not validate if val length < min threshold on first validation. Once field have been validated once and info
// about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
if (/key|input/.test(event.type)) if (!(this._ui && this._ui.validationInformationVisible) && this.getValue().length <= this.options.validationThreshold) return;
this.validate();
},
_resetUI: function _resetUI() {
// Reset all event listeners
this._failedOnce = false;
this._actualizeTriggers();
// Nothing to do if UI never initialized for this field
if ('undefined' === typeof this._ui) return;
// Reset all errors' li
this._ui.$errorsWrapper.removeClass('filled').children().remove();
// Reset validation class
this._resetClass();
// Reset validation flags and last validation result
this._ui.lastValidationResult = [];
this._ui.validationInformationVisible = false;
},
_destroyUI: function _destroyUI() {
this._resetUI();
if ('undefined' !== typeof this._ui) this._ui.$errorsWrapper.remove();
delete this._ui;
},
_successClass: function _successClass() {
this._ui.validationInformationVisible = true;
this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass);
},
_errorClass: function _errorClass() {
this._ui.validationInformationVisible = true;
this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass);
},
_resetClass: function _resetClass() {
this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass);
}
};
var ParsleyForm = function ParsleyForm(element, domOptions, options) {
this.__class__ = 'ParsleyForm';
this.$element = $(element);
this.domOptions = domOptions;
this.options = options;
this.parent = window.Parsley;
this.fields = [];
this.validationResult = null;
};
var ParsleyForm__statusMapping = { pending: null, resolved: true, rejected: false };
ParsleyForm.prototype = {
onSubmitValidate: function onSubmitValidate(event) {
var _this4 = this;
// This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior
if (true === event.parsley) return;
// If we didn't come here through a submit button, use the first one in the form
var $submitSource = this._$submitSource || this.$element.find('input[type="submit"], button[type="submit"]').first();
this._$submitSource = null;
this.$element.find('.parsley-synthetic-submit-button').prop('disabled', true);
if ($submitSource.is('[formnovalidate]')) return;
var promise = this.whenValidate({ event: event });
if ('resolved' === promise.state() && false !== this._trigger('submit')) {
// All good, let event go through. We make this distinction because browsers
// differ in their handling of `submit` being called from inside a submit event [#1047]
} else {
// Rejected or pending: cancel this submit
event.stopImmediatePropagation();
event.preventDefault();
if ('pending' === promise.state()) promise.done(function () {
_this4._submit($submitSource);
});
}
},
onSubmitButton: function onSubmitButton(event) {
this._$submitSource = $(event.currentTarget);
},
// internal
// _submit submits the form, this time without going through the validations.
// Care must be taken to "fake" the actual submit button being clicked.
_submit: function _submit($submitSource) {
if (false === this._trigger('submit')) return;
// Add submit button's data
if ($submitSource) {
var $synthetic = this.$element.find('.parsley-synthetic-submit-button').prop('disabled', false);
if (0 === $synthetic.length) $synthetic = $('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element);
$synthetic.attr({
name: $submitSource.attr('name'),
value: $submitSource.attr('value')
});
}
this.$element.trigger($.extend($.Event('submit'), { parsley: true }));
},
// Performs validation on fields while triggering events.
// @returns `true` if all validations succeeds, `false`
// if a failure is immediately detected, or `null`
// if dependant on a promise.
// Consider using `whenValidate` instead.
validate: function validate(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling validate on a parsley form without passing arguments as an object is deprecated.');
var _arguments = _slice.call(arguments);
var group = _arguments[0];
var force = _arguments[1];
var event = _arguments[2];
options = { group: group, force: force, event: event };
}
return ParsleyForm__statusMapping[this.whenValidate(options).state()];
},
whenValidate: function whenValidate() {
var _ParsleyUtils__default$all$done$fail$always,
_this5 = this;
var _ref7 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var group = _ref7.group;
var force = _ref7.force;
var event = _ref7.event;
this.submitEvent = event;
if (event) {
this.submitEvent = $.extend({}, event, { preventDefault: function preventDefault() {
ParsleyUtils__default.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
_this5.validationResult = false;
} });
}
this.validationResult = true;
// fire validate event to eventually modify things before very validation
this._trigger('validate');
// Refresh form DOM options and form's fields that could have changed
this._refreshFields();
var promises = this._withoutReactualizingFormOptions(function () {
return $.map(_this5.fields, function (field) {
return field.whenValidate({ force: force, group: group });
});
});
return (_ParsleyUtils__default$all$done$fail$always = ParsleyUtils__default.all(promises).done(function () {
_this5._trigger('success');
}).fail(function () {
_this5.validationResult = false;
_this5.focus();
_this5._trigger('error');
}).always(function () {
_this5._trigger('validated');
})).pipe.apply(_ParsleyUtils__default$all$done$fail$always, _toConsumableArray(this._pipeAccordingToValidationResult()));
},
// Iterate over refreshed fields, and stop on first failure.
// Returns `true` if all fields are valid, `false` if a failure is detected
// or `null` if the result depends on an unresolved promise.
// Prefer using `whenValid` instead.
isValid: function isValid(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling isValid on a parsley form without passing arguments as an object is deprecated.');
var _arguments2 = _slice.call(arguments);
var group = _arguments2[0];
var force = _arguments2[1];
options = { group: group, force: force };
}
return ParsleyForm__statusMapping[this.whenValid(options).state()];
},
// Iterate over refreshed fields and validate them.
// Returns a promise.
// A validation that immediately fails will interrupt the validations.
whenValid: function whenValid() {
var _this6 = this;
var _ref8 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var group = _ref8.group;
var force = _ref8.force;
this._refreshFields();
var promises = this._withoutReactualizingFormOptions(function () {
return $.map(_this6.fields, function (field) {
return field.whenValid({ group: group, force: force });
});
});
return ParsleyUtils__default.all(promises);
},
_refreshFields: function _refreshFields() {
return this.actualizeOptions()._bindFields();
},
_bindFields: function _bindFields() {
var _this7 = this;
var oldFields = this.fields;
this.fields = [];
this.fieldsMappedById = {};
this._withoutReactualizingFormOptions(function () {
_this7.$element.find(_this7.options.inputs).not(_this7.options.excluded).each(function (_, element) {
var fieldInstance = new window.Parsley.Factory(element, {}, _this7);
// Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && true !== fieldInstance.options.excluded) if ('undefined' === typeof _this7.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
_this7.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
_this7.fields.push(fieldInstance);
}
});
$.each(ParsleyUtils__default.difference(oldFields, _this7.fields), function (_, field) {
field._trigger('reset');
});
});
return this;
},
// Internal only.
// Looping on a form's fields to do validation or similar
// will trigger reactualizing options on all of them, which
// in turn will reactualize the form's options.
// To avoid calling actualizeOptions so many times on the form
// for nothing, _withoutReactualizingFormOptions temporarily disables
// the method actualizeOptions on this form while `fn` is called.
_withoutReactualizingFormOptions: function _withoutReactualizingFormOptions(fn) {
var oldActualizeOptions = this.actualizeOptions;
this.actualizeOptions = function () {
return this;
};
var result = fn();
this.actualizeOptions = oldActualizeOptions;
return result;
},
// Internal only.
// Shortcut to trigger an event
// Returns true iff event is not interrupted and default not prevented.
_trigger: function _trigger(eventName) {
return this.trigger('form:' + eventName);
}
};
var ConstraintFactory = function ConstraintFactory(parsleyField, name, requirements, priority, isDomConstraint) {
if (!/ParsleyField/.test(parsleyField.__class__)) throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
var validatorSpec = window.Parsley._validatorRegistry.validators[name];
var validator = new ParsleyValidator(validatorSpec);
$.extend(this, {
validator: validator,
name: name,
requirements: requirements,
priority: priority || parsleyField.options[name + 'Priority'] || validator.priority,
isDomConstraint: true === isDomConstraint
});
this._parseRequirements(parsleyField.options);
};
var capitalize = function capitalize(str) {
var cap = str[0].toUpperCase();
return cap + str.slice(1);
};
ConstraintFactory.prototype = {
validate: function validate(value, instance) {
var _validator;
return (_validator = this.validator).validate.apply(_validator, [value].concat(_toConsumableArray(this.requirementList), [instance]));
},
_parseRequirements: function _parseRequirements(options) {
var _this8 = this;
this.requirementList = this.validator.parseRequirements(this.requirements, function (key) {
return options[_this8.name + capitalize(key)];
});
}
};
var ParsleyField = function ParsleyField(field, domOptions, options, parsleyFormInstance) {
this.__class__ = 'ParsleyField';
this.$element = $(field);
// Set parent if we have one
if ('undefined' !== typeof parsleyFormInstance) {
this.parent = parsleyFormInstance;
}
this.options = options;
this.domOptions = domOptions;
// Initialize some properties
this.constraints = [];
this.constraintsByName = {};
this.validationResult = true;
// Bind constraints
this._bindConstraints();
};
var parsley_field__statusMapping = { pending: null, resolved: true, rejected: false };
ParsleyField.prototype = {
// # Public API
// Validate field and trigger some events for mainly `ParsleyUI`
// @returns `true`, an array of the validators that failed, or
// `null` if validation is not finished. Prefer using whenValidate
validate: function validate(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling validate on a parsley field without passing arguments as an object is deprecated.');
options = { options: options };
}
var promise = this.whenValidate(options);
if (!promise) // If excluded with `group` option
return true;
switch (promise.state()) {
case 'pending':
return null;
case 'resolved':
return true;
case 'rejected':
return this.validationResult;
}
},
// Validate field and trigger some events for mainly `ParsleyUI`
// @returns a promise that succeeds only when all validations do
// or `undefined` if field is not in the given `group`.
whenValidate: function whenValidate() {
var _whenValid$always$done$fail$always,
_this9 = this;
var _ref9 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var force = _ref9.force;
var group = _ref9.group;
// do not validate a field if not the same as given validation group
this.refreshConstraints();
if (group && !this._isInGroup(group)) return;
this.value = this.getValue();
// Field Validate event. `this.value` could be altered for custom needs
this._trigger('validate');
return (_whenValid$always$done$fail$always = this.whenValid({ force: force, value: this.value, _refreshed: true }).always(function () {
_this9._reflowUI();
}).done(function () {
_this9._trigger('success');
}).fail(function () {
_this9._trigger('error');
}).always(function () {
_this9._trigger('validated');
})).pipe.apply(_whenValid$always$done$fail$always, _toConsumableArray(this._pipeAccordingToValidationResult()));
},
hasConstraints: function hasConstraints() {
return 0 !== this.constraints.length;
},
// An empty optional field does not need validation
needsValidation: function needsValidation(value) {
if ('undefined' === typeof value) value = this.getValue();
// If a field is empty and not required, it is valid
// Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators
if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false;
return true;
},
_isInGroup: function _isInGroup(group) {
if ($.isArray(this.options.group)) return -1 !== $.inArray(group, this.options.group);
return this.options.group === group;
},
// Just validate field. Do not trigger any event.
// Returns `true` iff all constraints pass, `false` if there are failures,
// or `null` if the result can not be determined yet (depends on a promise)
// See also `whenValid`.
isValid: function isValid(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling isValid on a parsley field without passing arguments as an object is deprecated.');
var _arguments3 = _slice.call(arguments);
var force = _arguments3[0];
var value = _arguments3[1];
options = { force: force, value: value };
}
var promise = this.whenValid(options);
if (!promise) // Excluded via `group`
return true;
return parsley_field__statusMapping[promise.state()];
},
// Just validate field. Do not trigger any event.
// @returns a promise that succeeds only when all validations do
// or `undefined` if the field is not in the given `group`.
// The argument `force` will force validation of empty fields.
// If a `value` is given, it will be validated instead of the value of the input.
whenValid: function whenValid() {
var _this10 = this;
var _ref10 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref10$force = _ref10.force;
var force = _ref10$force === undefined ? false : _ref10$force;
var value = _ref10.value;
var group = _ref10.group;
var _refreshed = _ref10._refreshed;
// Recompute options and rebind constraints to have latest changes
if (!_refreshed) this.refreshConstraints();
// do not validate a field if not the same as given validation group
if (group && !this._isInGroup(group)) return;
this.validationResult = true;
// A field without constraint is valid
if (!this.hasConstraints()) return $.when();
// Value could be passed as argument, needed to add more power to 'field:validate'
if ('undefined' === typeof value || null === value) value = this.getValue();
if (!this.needsValidation(value) && true !== force) return $.when();
var groupedConstraints = this._getGroupedConstraints();
var promises = [];
$.each(groupedConstraints, function (_, constraints) {
// Process one group of constraints at a time, we validate the constraints
// and combine the promises together.
var promise = ParsleyUtils__default.all($.map(constraints, function (constraint) {
return _this10._validateConstraint(value, constraint);
}));
promises.push(promise);
if (promise.state() === 'rejected') return false; // Interrupt processing if a group has already failed
});
return ParsleyUtils__default.all(promises);
},
// @returns a promise
_validateConstraint: function _validateConstraint(value, constraint) {
var _this11 = this;
var result = constraint.validate(value, this);
// Map false to a failed promise
if (false === result) result = $.Deferred().reject();
// Make sure we return a promise and that we record failures
return ParsleyUtils__default.all([result]).fail(function (errorMessage) {
if (!(_this11.validationResult instanceof Array)) _this11.validationResult = [];
_this11.validationResult.push({
assert: constraint,
errorMessage: 'string' === typeof errorMessage && errorMessage
});
});
},
// @returns Parsley field computed value that could be overrided or configured in DOM
getValue: function getValue() {
var value;
// Value could be overriden in DOM or with explicit options
if ('function' === typeof this.options.value) value = this.options.value(this);else if ('undefined' !== typeof this.options.value) value = this.options.value;else value = this.$element.val();
// Handle wrong DOM or configurations
if ('undefined' === typeof value || null === value) return '';
return this._handleWhitespace(value);
},
// Actualize options that could have change since previous validation
// Re-bind accordingly constraints (could be some new, removed or updated)
refreshConstraints: function refreshConstraints() {
return this.actualizeOptions()._bindConstraints();
},
/**
* Add a new constraint to a field
*
* @param {String} name
* @param {Mixed} requirements optional
* @param {Number} priority optional
* @param {Boolean} isDomConstraint optional
*/
addConstraint: function addConstraint(name, requirements, priority, isDomConstraint) {
if (window.Parsley._validatorRegistry.validators[name]) {
var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint);
// if constraint already exist, delete it and push new version
if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name);
this.constraints.push(constraint);
this.constraintsByName[constraint.name] = constraint;
}
return this;
},
// Remove a constraint
removeConstraint: function removeConstraint(name) {
for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) {
this.constraints.splice(i, 1);
break;
}
delete this.constraintsByName[name];
return this;
},
// Update a constraint (Remove + re-add)
updateConstraint: function updateConstraint(name, parameters, priority) {
return this.removeConstraint(name).addConstraint(name, parameters, priority);
},
// # Internals
// Internal only.
// Bind constraints from config + options + DOM
_bindConstraints: function _bindConstraints() {
var constraints = [];
var constraintsByName = {};
// clean all existing DOM constraints to only keep javascript user constraints
for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) {
constraints.push(this.constraints[i]);
constraintsByName[this.constraints[i].name] = this.constraints[i];
}
this.constraints = constraints;
this.constraintsByName = constraintsByName;
// then re-add Parsley DOM-API constraints
for (var name in this.options) this.addConstraint(name, this.options[name], undefined, true);
// finally, bind special HTML5 constraints
return this._bindHtml5Constraints();
},
// Internal only.
// Bind specific HTML5 constraints to be HTML5 compliant
_bindHtml5Constraints: function _bindHtml5Constraints() {
// html5 required
if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true);
// html5 pattern
if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true);
// range
if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true);
// HTML5 min
else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true);
// HTML5 max
else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true);
// length
if ('undefined' !== typeof this.$element.attr('minlength') && 'undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('length', [this.$element.attr('minlength'), this.$element.attr('maxlength')], undefined, true);
// HTML5 minlength
else if ('undefined' !== typeof this.$element.attr('minlength')) this.addConstraint('minlength', this.$element.attr('minlength'), undefined, true);
// HTML5 maxlength
else if ('undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('maxlength', this.$element.attr('maxlength'), undefined, true);
// html5 types
var type = this.$element.attr('type');
if ('undefined' === typeof type) return this;
// Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise
if ('number' === type) {
return this.addConstraint('type', ['number', {
step: this.$element.attr('step'),
base: this.$element.attr('min') || this.$element.attr('value')
}], undefined, true);
// Regular other HTML5 supported types
} else if (/^(email|url|range)$/i.test(type)) {
return this.addConstraint('type', type, undefined, true);
}
return this;
},
// Internal only.
// Field is required if have required constraint without `false` value
_isRequired: function _isRequired() {
if ('undefined' === typeof this.constraintsByName.required) return false;
return false !== this.constraintsByName.required.requirements;
},
// Internal only.
// Shortcut to trigger an event
_trigger: function _trigger(eventName) {
return this.trigger('field:' + eventName);
},
// Internal only
// Handles whitespace in a value
// Use `data-parsley-whitespace="squish"` to auto squish input value
// Use `data-parsley-whitespace="trim"` to auto trim input value
_handleWhitespace: function _handleWhitespace(value) {
if (true === this.options.trimValue) ParsleyUtils__default.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"');
if ('squish' === this.options.whitespace) value = value.replace(/\s{2,}/g, ' ');
if ('trim' === this.options.whitespace || 'squish' === this.options.whitespace || true === this.options.trimValue) value = ParsleyUtils__default.trimString(value);
return value;
},
// Internal only.
// Returns the constraints, grouped by descending priority.
// The result is thus an array of arrays of constraints.
_getGroupedConstraints: function _getGroupedConstraints() {
if (false === this.options.priorityEnabled) return [this.constraints];
var groupedConstraints = [];
var index = {};
// Create array unique of priorities
for (var i = 0; i < this.constraints.length; i++) {
var p = this.constraints[i].priority;
if (!index[p]) groupedConstraints.push(index[p] = []);
index[p].push(this.constraints[i]);
}
// Sort them by priority DESC
groupedConstraints.sort(function (a, b) {
return b[0].priority - a[0].priority;
});
return groupedConstraints;
}
};
var parsley_field = ParsleyField;
var ParsleyMultiple = function ParsleyMultiple() {
this.__class__ = 'ParsleyFieldMultiple';
};
ParsleyMultiple.prototype = {
// Add new `$element` sibling for multiple field
addElement: function addElement($element) {
this.$elements.push($element);
return this;
},
// See `ParsleyField.refreshConstraints()`
refreshConstraints: function refreshConstraints() {
var fieldConstraints;
this.constraints = [];
// Select multiple special treatment
if (this.$element.is('select')) {
this.actualizeOptions()._bindConstraints();
return this;
}
// Gather all constraints for each input in the multiple group
for (var i = 0; i < this.$elements.length; i++) {
// Check if element have not been dynamically removed since last binding
if (!$('html').has(this.$elements[i]).length) {
this.$elements.splice(i, 1);
continue;
}
fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints;
for (var j = 0; j < fieldConstraints.length; j++) this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint);
}
return this;
},
// See `ParsleyField.getValue()`
getValue: function getValue() {
// Value could be overriden in DOM
if ('function' === typeof this.options.value) return this.options.value(this);else if ('undefined' !== typeof this.options.value) return this.options.value;
// Radio input case
if (this.$element.is('input[type=radio]')) return this._findRelated().filter(':checked').val() || '';
// checkbox input case
if (this.$element.is('input[type=checkbox]')) {
var values = [];
this._findRelated().filter(':checked').each(function () {
values.push($(this).val());
});
return values;
}
// Select multiple case
if (this.$element.is('select') && null === this.$element.val()) return [];
// Default case that should never happen
return this.$element.val();
},
_init: function _init() {
this.$elements = [this.$element];
return this;
}
};
var ParsleyFactory = function ParsleyFactory(element, options, parsleyFormInstance) {
this.$element = $(element);
// If the element has already been bound, returns its saved Parsley instance
var savedparsleyFormInstance = this.$element.data('Parsley');
if (savedparsleyFormInstance) {
// If the saved instance has been bound without a ParsleyForm parent and there is one given in this call, add it
if ('undefined' !== typeof parsleyFormInstance && savedparsleyFormInstance.parent === window.Parsley) {
savedparsleyFormInstance.parent = parsleyFormInstance;
savedparsleyFormInstance._resetOptions(savedparsleyFormInstance.options);
}
if ('object' === typeof options) {
$.extend(savedparsleyFormInstance.options, options);
}
return savedparsleyFormInstance;
}
// Parsley must be instantiated with a DOM element or jQuery $element
if (!this.$element.length) throw new Error('You must bind Parsley on an existing element.');
if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance');
this.parent = parsleyFormInstance || window.Parsley;
return this.init(options);
};
ParsleyFactory.prototype = {
init: function init(options) {
this.__class__ = 'Parsley';
this.__version__ = '2.4.2';
this.__id__ = ParsleyUtils__default.generateID();
// Pre-compute options
this._resetOptions(options);
// A ParsleyForm instance is obviously a `<form>` element but also every node that is not an input and has the `data-parsley-validate` attribute
if (this.$element.is('form') || ParsleyUtils__default.checkAttr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)) return this.bind('parsleyForm');
// Every other element is bound as a `ParsleyField` or `ParsleyFieldMultiple`
return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField');
},
isMultiple: function isMultiple() {
return this.$element.is('input[type=radio], input[type=checkbox]') || this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple');
},
// Multiples fields are a real nightmare :(
// Maybe some refactoring would be appreciated here...
handleMultiple: function handleMultiple() {
var _this12 = this;
var name;
var multiple;
var parsleyMultipleInstance;
// Handle multiple name
if (this.options.multiple) ; // We already have our 'multiple' identifier
else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) this.options.multiple = name = this.$element.attr('name');else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) this.options.multiple = this.$element.attr('id');
// Special select multiple input
if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) {
this.options.multiple = this.options.multiple || this.__id__;
return this.bind('parsleyFieldMultiple');
// Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it
} else if (!this.options.multiple) {
ParsleyUtils__default.warn('To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element);
return this;
}
// Remove special chars
this.options.multiple = this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, '');
// Add proper `data-parsley-multiple` to siblings if we have a valid multiple name
if ('undefined' !== typeof name) {
$('input[name="' + name + '"]').each(function (i, input) {
if ($(input).is('input[type=radio], input[type=checkbox]')) $(input).attr(_this12.options.namespace + 'multiple', _this12.options.multiple);
});
}
// Check here if we don't already have a related multiple instance saved
var $previouslyRelated = this._findRelated();
for (var i = 0; i < $previouslyRelated.length; i++) {
parsleyMultipleInstance = $($previouslyRelated.get(i)).data('Parsley');
if ('undefined' !== typeof parsleyMultipleInstance) {
if (!this.$element.data('ParsleyFieldMultiple')) {
parsleyMultipleInstance.addElement(this.$element);
}
break;
}
}
// Create a secret ParsleyField instance for every multiple field. It will be stored in `data('ParsleyFieldMultiple')`
// And will be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance
this.bind('parsleyField', true);
return parsleyMultipleInstance || this.bind('parsleyFieldMultiple');
},
// Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple`
bind: function bind(type, doNotStore) {
var parsleyInstance;
switch (type) {
case 'parsleyForm':
parsleyInstance = $.extend(new ParsleyForm(this.$element, this.domOptions, this.options), new ParsleyAbstract(), window.ParsleyExtend)._bindFields();
break;
case 'parsleyField':
parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), new ParsleyAbstract(), window.ParsleyExtend);
break;
case 'parsleyFieldMultiple':
parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), new ParsleyMultiple(), new ParsleyAbstract(), window.ParsleyExtend)._init();
break;
default:
throw new Error(type + 'is not a supported Parsley type');
}
if (this.options.multiple) ParsleyUtils__default.setAttr(this.$element, this.options.namespace, 'multiple', this.options.multiple);
if ('undefined' !== typeof doNotStore) {
this.$element.data('ParsleyFieldMultiple', parsleyInstance);
return parsleyInstance;
}
// Store the freshly bound instance in a DOM element for later access using jQuery `data()`
this.$element.data('Parsley', parsleyInstance);
// Tell the world we have a new ParsleyForm or ParsleyField instance!
parsleyInstance._actualizeTriggers();
parsleyInstance._trigger('init');
return parsleyInstance;
}
};
var vernums = $.fn.jquery.split('.');
if (parseInt(vernums[0]) <= 1 && parseInt(vernums[1]) < 8) {
throw "The loaded version of jQuery is too old. Please upgrade to 1.8.x or better.";
}
if (!vernums.forEach) {
ParsleyUtils__default.warn('Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim');
}
// Inherit `on`, `off` & `trigger` to Parsley:
var Parsley = $.extend(new ParsleyAbstract(), {
$element: $(document),
actualizeOptions: null,
_resetOptions: null,
Factory: ParsleyFactory,
version: '2.4.2'
});
// Supplement ParsleyField and Form with ParsleyAbstract
// This way, the constructors will have access to those methods
$.extend(parsley_field.prototype, ParsleyUI.Field, ParsleyAbstract.prototype);
$.extend(ParsleyForm.prototype, ParsleyUI.Form, ParsleyAbstract.prototype);
// Inherit actualizeOptions and _resetOptions:
$.extend(ParsleyFactory.prototype, ParsleyAbstract.prototype);
// ### jQuery API
// `$('.elem').parsley(options)` or `$('.elem').psly(options)`
$.fn.parsley = $.fn.psly = function (options) {
if (this.length > 1) {
var instances = [];
this.each(function () {
instances.push($(this).parsley(options));
});
return instances;
}
// Return undefined if applied to non existing DOM element
if (!$(this).length) {
ParsleyUtils__default.warn('You must bind Parsley on an existing element.');
return;
}
return new ParsleyFactory(this, options);
};
// ### ParsleyField and ParsleyForm extension
// Ensure the extension is now defined if it wasn't previously
if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {};
// ### Parsley config
// Inherit from ParsleyDefault, and copy over any existing values
Parsley.options = $.extend(ParsleyUtils__default.objectCreate(ParsleyDefaults), window.ParsleyConfig);
window.ParsleyConfig = Parsley.options; // Old way of accessing global options
// ### Globals
window.Parsley = window.psly = Parsley;
window.ParsleyUtils = ParsleyUtils__default;
// ### Define methods that forward to the registry, and deprecate all access except through window.Parsley
var registry = window.Parsley._validatorRegistry = new ParsleyValidatorRegistry(window.ParsleyConfig.validators, window.ParsleyConfig.i18n);
window.ParsleyValidator = {};
$.each('setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator'.split(' '), function (i, method) {
window.Parsley[method] = $.proxy(registry, method);
window.ParsleyValidator[method] = function () {
var _window$Parsley;
ParsleyUtils__default.warnOnce('Accessing the method \'' + method + '\' through ParsleyValidator is deprecated. Simply call \'window.Parsley.' + method + '(...)\'');
return (_window$Parsley = window.Parsley)[method].apply(_window$Parsley, arguments);
};
});
// ### ParsleyUI
// Deprecated global object
window.Parsley.UI = ParsleyUI;
window.ParsleyUI = {
removeError: function removeError(instance, name, doNotUpdateClass) {
var updateClass = true !== doNotUpdateClass;
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'removeError\' on the instance directly. Please comment in issue 1073 as to your need to call this method.');
return instance.removeError(name, { updateClass: updateClass });
},
getErrorsMessages: function getErrorsMessages(instance) {
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'getErrorsMessages\' on the instance directly.');
return instance.getErrorsMessages();
}
};
$.each('addError updateError'.split(' '), function (i, method) {
window.ParsleyUI[method] = function (instance, name, message, assert, doNotUpdateClass) {
var updateClass = true !== doNotUpdateClass;
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'' + method + '\' on the instance directly. Please comment in issue 1073 as to your need to call this method.');
return instance[method](name, { message: message, assert: assert, updateClass: updateClass });
};
});
// ### PARSLEY auto-binding
// Prevent it by setting `ParsleyConfig.autoBind` to `false`
if (false !== window.ParsleyConfig.autoBind) {
$(function () {
// Works only on `data-parsley-validate`.
if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley();
});
}
var o = $({});
var deprecated = function deprecated() {
ParsleyUtils__default.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley");
};
// Returns an event handler that calls `fn` with the arguments it expects
function adapt(fn, context) {
// Store to allow unbinding
if (!fn.parsleyAdaptedCallback) {
fn.parsleyAdaptedCallback = function () {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(this);
fn.apply(context || o, args);
};
}
return fn.parsleyAdaptedCallback;
}
var eventPrefix = 'parsley:';
// Converts 'parsley:form:validate' into 'form:validate'
function eventName(name) {
if (name.lastIndexOf(eventPrefix, 0) === 0) return name.substr(eventPrefix.length);
return name;
}
// $.listen is deprecated. Use Parsley.on instead.
$.listen = function (name, callback) {
var context;
deprecated();
if ('object' === typeof arguments[1] && 'function' === typeof arguments[2]) {
context = arguments[1];
callback = arguments[2];
}
if ('function' !== typeof callback) throw new Error('Wrong parameters');
window.Parsley.on(eventName(name), adapt(callback, context));
};
$.listenTo = function (instance, name, fn) {
deprecated();
if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance');
if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong parameters');
instance.on(eventName(name), adapt(fn));
};
$.unsubscribe = function (name, fn) {
deprecated();
if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong arguments');
window.Parsley.off(eventName(name), fn.parsleyAdaptedCallback);
};
$.unsubscribeTo = function (instance, name) {
deprecated();
if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance');
instance.off(eventName(name));
};
$.unsubscribeAll = function (name) {
deprecated();
window.Parsley.off(eventName(name));
$('form,input,textarea,select').each(function () {
var instance = $(this).data('Parsley');
if (instance) {
instance.off(eventName(name));
}
});
};
// $.emit is deprecated. Use jQuery events instead.
$.emit = function (name, instance) {
var _instance;
deprecated();
var instanceGiven = instance instanceof parsley_field || instance instanceof ParsleyForm;
var args = Array.prototype.slice.call(arguments, instanceGiven ? 2 : 1);
args.unshift(eventName(name));
if (!instanceGiven) {
instance = window.Parsley;
}
(_instance = instance).trigger.apply(_instance, _toConsumableArray(args));
};
var pubsub = {};
$.extend(true, Parsley, {
asyncValidators: {
'default': {
fn: function fn(xhr) {
// By default, only status 2xx are deemed successful.
// Note: we use status instead of state() because responses with status 200
// but invalid messages (e.g. an empty body for content type set to JSON) will
// result in state() === 'rejected'.
return xhr.status >= 200 && xhr.status < 300;
},
url: false
},
reverse: {
fn: function fn(xhr) {
// If reverse option is set, a failing ajax request is considered successful
return xhr.status < 200 || xhr.status >= 300;
},
url: false
}
},
addAsyncValidator: function addAsyncValidator(name, fn, url, options) {
Parsley.asyncValidators[name] = {
fn: fn,
url: url || false,
options: options || {}
};
return this;
}
});
Parsley.addValidator('remote', {
requirementType: {
'': 'string',
'validator': 'string',
'reverse': 'boolean',
'options': 'object'
},
validateString: function validateString(value, url, options, instance) {
var data = {};
var ajaxOptions;
var csr;
var validator = options.validator || (true === options.reverse ? 'reverse' : 'default');
if ('undefined' === typeof Parsley.asyncValidators[validator]) throw new Error('Calling an undefined async validator: `' + validator + '`');
url = Parsley.asyncValidators[validator].url || url;
// Fill current value
if (url.indexOf('{value}') > -1) {
url = url.replace('{value}', encodeURIComponent(value));
} else {
data[instance.$element.attr('name') || instance.$element.attr('id')] = value;
}
// Merge options passed in from the function with the ones in the attribute
var remoteOptions = $.extend(true, options.options || {}, Parsley.asyncValidators[validator].options);
// All `$.ajax(options)` could be overridden or extended directly from DOM in `data-parsley-remote-options`
ajaxOptions = $.extend(true, {}, {
url: url,
data: data,
type: 'GET'
}, remoteOptions);
// Generate store key based on ajax options
instance.trigger('field:ajaxoptions', instance, ajaxOptions);
csr = $.param(ajaxOptions);
// Initialise querry cache
if ('undefined' === typeof Parsley._remoteCache) Parsley._remoteCache = {};
// Try to retrieve stored xhr
var xhr = Parsley._remoteCache[csr] = Parsley._remoteCache[csr] || $.ajax(ajaxOptions);
var handleXhr = function handleXhr() {
var result = Parsley.asyncValidators[validator].fn.call(instance, xhr, url, options);
if (!result) // Map falsy results to rejected promise
result = $.Deferred().reject();
return $.when(result);
};
return xhr.then(handleXhr, handleXhr);
},
priority: -1
});
Parsley.on('form:submit', function () {
Parsley._remoteCache = {};
});
window.ParsleyExtend.addAsyncValidator = function () {
ParsleyUtils.warnOnce('Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`');
return Parsley.addAsyncValidator.apply(Parsley, arguments);
};
// This is included with the Parsley library itself,
// thus there is no use in adding it to your project.
Parsley.addMessages('en', {
defaultMessage: "This value seems to be invalid.",
type: {
email: "This value should be a valid email.",
url: "This value should be a valid url.",
number: "This value should be a valid number.",
integer: "This value should be a valid integer.",
digits: "This value should be digits.",
alphanum: "This value should be alphanumeric."
},
notblank: "This value should not be blank.",
required: "This value is required.",
pattern: "This value seems to be invalid.",
min: "This value should be greater than or equal to %s.",
max: "This value should be lower than or equal to %s.",
range: "This value should be between %s and %s.",
minlength: "This value is too short. It should have %s characters or more.",
maxlength: "This value is too long. It should have %s characters or fewer.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "You must select at least %s choices.",
maxcheck: "You must select %s choices or fewer.",
check: "You must select between %s and %s choices.",
equalto: "This value should be the same."
});
Parsley.setLocale('en');
/**
* inputevent - Alleviate browser bugs for input events
* https://github.com/marcandre/inputevent
* @version v0.0.3 - (built Thu, Apr 14th 2016, 5:58 pm)
* @author Marc-Andre Lafortune <github@marc-andre.ca>
* @license MIT
*/
function InputEvent() {
var _this13 = this;
var globals = window || global;
// Slightly odd way construct our object. This way methods are force bound.
// Used to test for duplicate library.
$.extend(this, {
// For browsers that do not support isTrusted, assumes event is native.
isNativeEvent: function isNativeEvent(evt) {
return evt.originalEvent && evt.originalEvent.isTrusted !== false;
},
fakeInputEvent: function fakeInputEvent(evt) {
if (_this13.isNativeEvent(evt)) {
$(evt.target).trigger('input');
}
},
misbehaves: function misbehaves(evt) {
if (_this13.isNativeEvent(evt)) {
_this13.behavesOk(evt);
$(document).on('change.inputevent', evt.data.selector, _this13.fakeInputEvent);
_this13.fakeInputEvent(evt);
}
},
behavesOk: function behavesOk(evt) {
if (_this13.isNativeEvent(evt)) {
$(document) // Simply unbinds the testing handler
.off('input.inputevent', evt.data.selector, _this13.behavesOk).off('change.inputevent', evt.data.selector, _this13.misbehaves);
}
},
// Bind the testing handlers
install: function install() {
if (globals.inputEventPatched) {
return;
}
globals.inputEventPatched = '0.0.3';
var _arr = ['select', 'input[type="checkbox"]', 'input[type="radio"]', 'input[type="file"]'];
for (var _i = 0; _i < _arr.length; _i++) {
var selector = _arr[_i];
$(document).on('input.inputevent', selector, { selector: selector }, _this13.behavesOk).on('change.inputevent', selector, { selector: selector }, _this13.misbehaves);
}
},
uninstall: function uninstall() {
delete globals.inputEventPatched;
$(document).off('.inputevent');
}
});
};
var inputevent = new InputEvent();
inputevent.install();
var parsley = Parsley;
return parsley;
});
//# sourceMappingURL=parsley.js.map
|
public/js/components/App.js | richardison/audition-project | import React from 'react';
import MessageList from './MessageList.js';
import MessageForm from './MessageForm.js';
import Instructions from './Instructions.js';
import { Col } from 'react-bootstrap';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: []
}
this.fetchMessages = this.fetchMessages.bind(this);
}
fetchMessages() {
return fetch('/messages')
.then( (res) => res.json())
.then( (messages) => {
this.setState({messages});
})
.catch(error => {
console.log(`Error getting messages: ${error}`);
});
}
componentWillMount() {
document.body.style.backgroundColor = "#708090";
}
componentDidMount() {
this.fetchMessages()
}
render() {
return (
<div className="app">
<Col md={6} mdOffset={3}>
<h1> Audition Project </h1>
<Instructions />
<MessageForm
fetchMessages = {this.fetchMessages()}
/>
<MessageList
messages = {this.state.messages}
/>
</Col>
</div>
);
}
}
|
www/src/pages/404.js | niklasvh/html2canvas | import React from 'react';
import Layout from '../components/layout';
const NotFoundPage = () =>
<Layout>
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</Layout>;
export default NotFoundPage;
|
vgdb-frontend/src/components/loader/Loader.js | mattruston/idb | import React, { Component } from 'react';
import './Loader.css';
class Loader extends Component {
render() {
return (
<div className="loading-container">
<div className="sk-folding-cube">
<div className="sk-cube1 sk-cube"></div>
<div className="sk-cube2 sk-cube"></div>
<div className="sk-cube4 sk-cube"></div>
<div className="sk-cube3 sk-cube"></div>
</div>
</div>
);
}
}
export default Loader; |
ajax/libs/flocks.js/0.15.2/flocks.js | panshuiqing/cdnjs | /** @jsx React.DOM */
/* jshint node: true, browser: true, newcap: false */
/**
* The Flocks library module.
*
* @module Flocks
* @main Flocks
* @class Flocks
*/
// if it's in a <script> it's defined already
// otherwise assume commonjs
if (typeof React === 'undefined') {
var React = require('react');
}
// wrap the remainder
(function() {
'use strict';
var initialized = false,
updateBlocks = 0,
dirty = false,
tagtype,
handler = function(Ignored) { return true; },
finalizer = function() { return true; },
prevFCtx = {},
nextFCtx = {},
flocks2_ctxs = { flocks2context: React.PropTypes.object };
function flocksLog(Level, Message) {
if (typeof Level === 'string') {
if (array_member(Level, ['warn','debug','error','log','info','exception','assert'])) {
console[Level]('Flocks2 [' + Level + '] ' + Message.toString());
} else {
console.log('Flocks2 [Unknown level] ' + Message.toString());
}
} else if (isUndefined(nextFCtx.flocks_config)) {
console.log('Flocks2 pre-config [' + Level.toString() + '] ' + Message.toString());
} else if (nextFCtx.flocks_config.log_level >= Level) {
console.log('Flocks2 [' + Level.toString() + '] ' + Message.toString());
}
}
function enforceString(On, Label) {
if (typeof On !== 'string') {
throw Label || 'Argument must be a string';
}
}
function enforceArray(On, Label) {
if (!isArray(On)) {
throw Label || 'Argument must be an array';
}
}
function enforceNonArrayObject(On, Label) {
if (!isNonArrayObject(On)) {
throw Label || 'Argument must be a non-array object';
}
}
function isArray(maybeArray) {
return (Object.prototype.toString.call(maybeArray) === '[object Array]');
}
function isUndefined(maybeUndefined) {
return (typeof maybeUndefined === 'undefined');
}
function isNonArrayObject(maybeArray) {
if (typeof maybeArray !== 'object') { return false; }
if (Object.prototype.toString.call(maybeArray) === '[object Array]') { return false; }
return true;
}
function setByKey(Key, MaybeValue) {
enforceString(Key, "Flocks2 set/2 must take a string for its key");
nextFCtx[Key] = MaybeValue;
flocksLog(1, " - Flocks2 setByKey \"" + Key + "\"");
attemptUpdate();
}
// function setByPath(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByPath stub' ); attemptUpdate(); } // whargarbl todo
// function setByObject(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByObject stub'); attemptUpdate(); } // whargarbl todo
function set(Key, MaybeValue) {
flocksLog(3, ' - Flocks2 multi-set');
if (typeof Key === 'string') { setByKey(Key, MaybeValue); }
// else if (isArray(Key)) { setByPath(Key, MaybeValue); } // whargarbl todo
// else if (isNonArrayObject(Key)) { setByObject(Key); } // whargarbl todo
else { throw 'Flocks2 set/1,2 key must be a string or an array'; }
}
function update(SparseObject) {
console.log('update - whargarbl stub');
enforceNonArrayObject(SparseObject, 'Flocks2 update/1 must take a plain object');
}
function lock() {
++updateBlocks;
}
function unlock() {
if (updateBlocks <= 0) { throw 'unlock()ed with no lock!'; }
--updateBlocks;
attemptUpdate();
}
function clone(obj) {
if ((null === obj) || ('object' != typeof obj)) { return obj; }
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; }
}
return copy;
}
// ... lol
function array_member(Item, Array) {
return (!!(~( Array.indexOf(Item, 0) )));
}
function attemptUpdate() {
flocksLog(3, ' - Flocks2 attempting update');
dirty = true;
if (!(initialized)) {
flocksLog(1, ' x Flocks2 skipped update: root is not initialized');
return null;
}
if (updateBlocks) {
flocksLog(1, ' x Flocks2 skipped update: lock count updateBlocks is non-zero');
return null;
}
/* whargarbl see issue #9 https://github.com/StoneCypher/flocks.js/issues/9
if (deepCompare(nextFCtx, prevFCtx)) {
flocksLog(2, ' x Flocks2 skipped update: no update to state');
return true;
}
*/
if (!(handler(nextFCtx))) {
flocksLog(0, ' ! Flocks2 rolling back update: handler rejected propset');
nextFCtx = prevFCtx;
dirty = false;
return null;
}
prevFCtx = nextFCtx;
flocksLog(3, ' - Flocks2 update passed');
React.render( React.createFactory(tagtype)( { flocks2context: nextFCtx } ), document.body );
dirty = false;
flocksLog(3, ' - Flocks2 update complete; finalizing');
finalizer();
return true;
}
function create(iFlocksConfig, iFlocksData) {
var FlocksConfig = iFlocksConfig || {},
FlocksData = iFlocksData || {},
target = FlocksConfig.target || document.body,
stub = function() { window.alert('whargarbl stub'); attemptUpdate(); },
updater = {
get : stub,
set : set,
override : stub,
clear : stub,
update : update,
lock : lock,
unlock : unlock
};
FlocksConfig.log_level = FlocksConfig.log_level || -1;
tagtype = FlocksConfig.control;
FlocksData.flocks_config = FlocksConfig;
nextFCtx = FlocksData;
flocksLog(1, 'Flocks2 root creation begins');
if (!(tagtype)) { throw 'Flocks2 fatal error: must provide a control in create/2 FlocksConfig'; }
if (FlocksConfig.handler) { handler = FlocksConfig.handler; flocksLog(3, ' - Flocks2 handler assigned' ); }
if (FlocksConfig.finalizer) { finalizer = FlocksConfig.finalizer; flocksLog(3, ' - Flocks2 finalizer assigned'); }
if (FlocksConfig.preventAutoContext) {
flocksLog(2, ' - Flocks2 skipping auto-context');
} else {
flocksLog(2, ' - Flocks2 engaging auto-context');
this.fctx = clone(nextFCtx);
}
flocksLog(3, 'Flocks2 creation finished; initializing');
initialized = true;
attemptUpdate();
flocksLog(3, 'Flocks2 expose updater');
this.fupd = updater;
this.fset = updater.set;
this.flock = updater.lock;
this.funlock = updater.unlock;
this.fupdate = updater.update;
flocksLog(3, 'Flocks2 initialization finished');
return updater;
}
var Mixin = {
contextTypes : flocks2_ctxs,
childContextTypes : flocks2_ctxs,
componentWillMount: function() {
flocksLog(1, ' - Flocks2 component will mount: ' + this.constructor.displayName);
flocksLog(3, isUndefined(this.props.flocks2context) ? ' - No F2 Context Prop' : ' - F2 Context Prop found');
flocksLog(3, isUndefined(this.context.flocks2context) ? ' - No F2 Context' : ' - F2 Context found');
if (this.props.flocks2context) {
this.context.flocks2context = this.props.flocks2context;
}
this.fupdate = function(Obj) { update(Obj); };
this.fset = function(K,V) { set(K,V); };
this.flock = function() { lock(); };
this.funlock = function() { unlock(); };
this.fctx = this.context.flocks2context;
},
getChildContext: function() {
return this.context;
}
};
function atLeastFlocks(OriginalList) {
if (isUndefined(OriginalList)) {
return [ Mixin ];
}
if (isArray(OriginalList)) {
if (array_member(Mixin, OriginalList)) {
return OriginalList;
} else {
var NewList = clone(OriginalList);
NewList.push(Mixin);
return NewList;
}
}
throw 'Original mixin list must be an array or undefined!';
}
function createClass(spec) {
spec.mixins = atLeastFlocks(spec.mixins);
return React.createClass(spec);
}
var exports = {
plumbing : Mixin,
createClass : createClass,
mount : create,
clone : clone,
isArray : isArray,
isUndefined : isUndefined,
isNonArrayObject : isNonArrayObject,
enforceString : enforceString,
enforceArray : enforceArray,
enforceNonArrayObject : enforceNonArrayObject,
atLeastFlocks : atLeastFlocks
};
if (typeof module !== 'undefined') {
module.exports = exports;
} else {
window.flocks = exports;
}
}());
|
fields/types/email/EmailField.js | matthieugayon/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
/*
TODO:
- gravatar
- validate email address
*/
module.exports = Field.create({
displayName: 'EmailField',
renderField () {
return (
<FormInput
name={this.props.path}
ref="focusTarget"
value={this.props.value}
onChange={this.valueChanged}
autoComplete="off"
type="email"
/>
);
},
renderValue () {
return this.props.value ? (
<FormInput noedit href={'mailto:' + this.props.value}>{this.props.value}</FormInput>
) : (
<FormInput noedit>(not set)</FormInput>
);
},
});
|
src/svg-icons/device/signal-wifi-0-bar.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/>
</SvgIcon>
);
DeviceSignalWifi0Bar = pure(DeviceSignalWifi0Bar);
DeviceSignalWifi0Bar.displayName = 'DeviceSignalWifi0Bar';
export default DeviceSignalWifi0Bar;
|
client/src/js/components/Display/Display.js | Siddharth11/iTunes-Remote | // essentials
import React from 'react'
import DisplayTrack from './DisplayTrack'
import DisplayProgress from './DisplayProgress'
import TogglePlaylist from './TogglePlaylist'
import ToggleTracklist from './ToggleTracklist'
import Visual from './Visual'
const Display = () => (
<div className="display" >
<Visual />
<TogglePlaylist />
<ToggleTracklist />
<DisplayTrack />
<DisplayProgress />
</div>
)
export default Display |
packages/cf-component-card/test/CardToolbarLink.js | koddsson/cf-ui | import React from 'react';
import renderer from 'react-test-renderer';
import CardToolbarLink from '../src/CardToolbarLink';
test('should render', () => {
const component = renderer.create(
<CardToolbarLink id="link" isActive={false} onClick={() => {}}>
CardToolbarLink
</CardToolbarLink>
);
expect(component.toJSON()).toMatchSnapshot();
});
test('should render with isActive', () => {
const component = renderer.create(
<CardToolbarLink id="link" isActive={true} onClick={() => {}}>
CardToolbarLink
</CardToolbarLink>
);
expect(component.toJSON()).toMatchSnapshot();
});
|
packages/material-ui-icons/src/Wallpaper.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Wallpaper = props =>
<SvgIcon {...props}>
<path d="M4 4h7V2H4c-1.1 0-2 .9-2 2v7h2V4zm6 9l-4 5h12l-3-4-2.03 2.71L10 13zm7-4.5c0-.83-.67-1.5-1.5-1.5S14 7.67 14 8.5s.67 1.5 1.5 1.5S17 9.33 17 8.5zM20 2h-7v2h7v7h2V4c0-1.1-.9-2-2-2zm0 18h-7v2h7c1.1 0 2-.9 2-2v-7h-2v7zM4 13H2v7c0 1.1.9 2 2 2h7v-2H4v-7z" />
</SvgIcon>;
Wallpaper = pure(Wallpaper);
Wallpaper.muiName = 'SvgIcon';
export default Wallpaper;
|
node_modules/react-router/es6/Router.js | 937aaron/reduxblog | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import createHashHistory from 'history/lib/createHashHistory';
import useQueries from 'history/lib/useQueries';
import invariant from 'invariant';
import React from 'react';
import createTransitionManager from './createTransitionManager';
import { routes } from './InternalPropTypes';
import RouterContext from './RouterContext';
import { createRoutes } from './RouteUtils';
import { createRouterObject, createRoutingHistory } from './RouterUtils';
import warning from './routerWarning';
function isDeprecatedHistory(history) {
return !history || !history.__v2_compatible__;
}
/* istanbul ignore next: sanity check */
function isUnsupportedHistory(history) {
// v3 histories expose getCurrentLocation, but aren't currently supported.
return history && history.getCurrentLocation;
}
var _React$PropTypes = React.PropTypes;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RouterContext> with all the props
* it needs each time the URL changes.
*/
var Router = React.createClass({
displayName: 'Router',
propTypes: {
history: object,
children: routes,
routes: routes, // alias for children
render: func,
createElement: func,
onError: func,
onUpdate: func,
// Deprecated:
parseQueryString: func,
stringifyQuery: func,
// PRIVATE: For client-side rehydration of server match.
matchContext: object
},
getDefaultProps: function getDefaultProps() {
return {
render: function render(props) {
return React.createElement(RouterContext, props);
}
};
},
getInitialState: function getInitialState() {
return {
location: null,
routes: null,
params: null,
components: null
};
},
handleError: function handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error);
} else {
// Throw errors by default so we don't silently swallow them!
throw error; // This error probably occurred in getChildRoutes or getComponents.
}
},
componentWillMount: function componentWillMount() {
var _this = this;
var _props = this.props;
var parseQueryString = _props.parseQueryString;
var stringifyQuery = _props.stringifyQuery;
process.env.NODE_ENV !== 'production' ? warning(!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : void 0;
var _createRouterObjects = this.createRouterObjects();
var history = _createRouterObjects.history;
var transitionManager = _createRouterObjects.transitionManager;
var router = _createRouterObjects.router;
this._unlisten = transitionManager.listen(function (error, state) {
if (error) {
_this.handleError(error);
} else {
_this.setState(state, _this.props.onUpdate);
}
});
this.history = history;
this.router = router;
},
createRouterObjects: function createRouterObjects() {
var matchContext = this.props.matchContext;
if (matchContext) {
return matchContext;
}
var history = this.props.history;
var _props2 = this.props;
var routes = _props2.routes;
var children = _props2.children;
!!isUnsupportedHistory(history) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v3.x. ' + 'This version of React Router is not compatible with v3 history ' + 'objects. Please use history v2.x instead.') : invariant(false) : void 0;
if (isDeprecatedHistory(history)) {
history = this.wrapDeprecatedHistory(history);
}
var transitionManager = createTransitionManager(history, createRoutes(routes || children));
var router = createRouterObject(history, transitionManager);
var routingHistory = createRoutingHistory(history, transitionManager);
return { history: routingHistory, transitionManager: transitionManager, router: router };
},
wrapDeprecatedHistory: function wrapDeprecatedHistory(history) {
var _props3 = this.props;
var parseQueryString = _props3.parseQueryString;
var stringifyQuery = _props3.stringifyQuery;
var createHistory = void 0;
if (history) {
process.env.NODE_ENV !== 'production' ? warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : void 0;
createHistory = function createHistory() {
return history;
};
} else {
process.env.NODE_ENV !== 'production' ? warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : void 0;
createHistory = createHashHistory;
}
return useQueries(createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery });
},
/* istanbul ignore next: sanity check */
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0;
process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0;
},
componentWillUnmount: function componentWillUnmount() {
if (this._unlisten) this._unlisten();
},
render: function render() {
var _state = this.state;
var location = _state.location;
var routes = _state.routes;
var params = _state.params;
var components = _state.components;
var _props4 = this.props;
var createElement = _props4.createElement;
var render = _props4.render;
var props = _objectWithoutProperties(_props4, ['createElement', 'render']);
if (location == null) return null; // Async match
// Only forward non-Router-specific props to routing context, as those are
// the only ones that might be custom routing context props.
Object.keys(Router.propTypes).forEach(function (propType) {
return delete props[propType];
});
return render(_extends({}, props, {
history: this.history,
router: this.router,
location: location,
routes: routes,
params: params,
components: components,
createElement: createElement
}));
}
});
export default Router; |
packages/material-ui-icons/src/LensSharp.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" />
, 'LensSharp');
|
warmup/bower_components/react/react-with-addons.min.js | paf31/lambdaconf-2015 | /**
* React (with addons) v0.12.2
*
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,function(e){var n=t[a][1][e];return o(n?n:e)},l,l.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t){"use strict";var n=e("./LinkedStateMixin"),r=e("./React"),o=e("./ReactComponentWithPureRenderMixin"),i=e("./ReactCSSTransitionGroup"),a=e("./ReactTransitionGroup"),s=e("./ReactUpdates"),u=e("./cx"),c=e("./cloneWithProps"),l=e("./update");r.addons={CSSTransitionGroup:i,LinkedStateMixin:n,PureRenderMixin:o,TransitionGroup:a,batchedUpdates:s.batchedUpdates,classSet:u,cloneWithProps:c,update:l},t.exports=r},{"./LinkedStateMixin":25,"./React":31,"./ReactCSSTransitionGroup":34,"./ReactComponentWithPureRenderMixin":39,"./ReactTransitionGroup":87,"./ReactUpdates":88,"./cloneWithProps":110,"./cx":115,"./update":154}],2:[function(e,t){"use strict";var n=e("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":122}],3:[function(e,t){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ExecutionEnvironment"),s=e("./SyntheticInputEvent"),u=e("./keyOf"),c=a.canUseDOM&&"TextEvent"in window&&!("documentMode"in document||n()),l=32,p=String.fromCharCode(l),d=o.topLevelTypes,f={beforeInput:{phasedRegistrationNames:{bubbled:u({onBeforeInput:null}),captured:u({onBeforeInputCapture:null})},dependencies:[d.topCompositionEnd,d.topKeyPress,d.topTextInput,d.topPaste]}},h=null,m=!1,v={eventTypes:f,extractEvents:function(e,t,n,o){var a;if(c)switch(e){case d.topKeyPress:var u=o.which;if(u!==l)return;m=!0,a=p;break;case d.topTextInput:if(a=o.data,a===p&&m)return;break;default:return}else{switch(e){case d.topPaste:h=null;break;case d.topKeyPress:o.which&&!r(o)&&(h=String.fromCharCode(o.which));break;case d.topCompositionEnd:h=o.data}if(null===h)return;a=h}if(a){var v=s.getPooled(f.beforeInput,n,o);return v.data=a,h=null,i.accumulateTwoPhaseDispatches(v),v}}};t.exports=v},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./SyntheticInputEvent":98,"./keyOf":144}],4:[function(e,t){var n=e("./invariant"),r={addClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.add(t):r.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.remove(t):r.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?r.addClass:r.removeClass)(e,t)},hasClass:function(e,t){return n(!/\s/.test(t)),e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}};t.exports=r},{"./invariant":137}],5:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={columnCount:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeOpacity:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};t.exports=a},{}],6:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./ExecutionEnvironment"),o=(e("./camelizeStyleName"),e("./dangerousStyleValue")),i=e("./hyphenateStyleName"),a=e("./memoizeStringOnly"),s=(e("./warning"),a(function(e){return i(e)})),u="cssFloat";r.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(u="styleFloat");var c={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=o(n,r)+";")}return t||null},setValueForStyles:function(e,t){var r=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=o(i,t[i]);if("float"===i&&(i=u),a)r[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var c in s)r[c]="";else r[i]=""}}}};t.exports=c},{"./CSSProperty":5,"./ExecutionEnvironment":23,"./camelizeStyleName":109,"./dangerousStyleValue":116,"./hyphenateStyleName":135,"./memoizeStringOnly":146,"./warning":155}],7:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),o=e("./Object.assign"),i=e("./invariant");o(n.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){i(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./invariant":137}],8:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=M.getPooled(P.change,w,e);E.accumulateTwoPhaseDispatches(t),R.batchedUpdates(o,t)}function o(e){g.enqueueEvents(e),g.processEventQueue()}function i(e,t){T=e,w=t,T.attachEvent("onchange",r)}function a(){T&&(T.detachEvent("onchange",r),T=null,w=null)}function s(e,t,n){return e===x.topChange?n:void 0}function u(e,t,n){e===x.topFocus?(a(),i(t,n)):e===x.topBlur&&a()}function c(e,t){T=e,w=t,_=e.value,S=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(T,"value",k),T.attachEvent("onpropertychange",p)}function l(){T&&(delete T.value,T.detachEvent("onpropertychange",p),T=null,w=null,_=null,S=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==_&&(_=t,r(e))}}function d(e,t,n){return e===x.topInput?n:void 0}function f(e,t,n){e===x.topFocus?(l(),c(t,n)):e===x.topBlur&&l()}function h(e){return e!==x.topSelectionChange&&e!==x.topKeyUp&&e!==x.topKeyDown||!T||T.value===_?void 0:(_=T.value,w)}function m(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function v(e,t,n){return e===x.topClick?n:void 0}var y=e("./EventConstants"),g=e("./EventPluginHub"),E=e("./EventPropagators"),C=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),b=e("./isEventSupported"),O=e("./isTextInputElement"),D=e("./keyOf"),x=y.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:D({onChange:null}),captured:D({onChangeCapture:null})},dependencies:[x.topBlur,x.topChange,x.topClick,x.topFocus,x.topInput,x.topKeyDown,x.topKeyUp,x.topSelectionChange]}},T=null,w=null,_=null,S=null,N=!1;C.canUseDOM&&(N=b("change")&&(!("documentMode"in document)||document.documentMode>8));var I=!1;C.canUseDOM&&(I=b("input")&&(!("documentMode"in document)||document.documentMode>9));var k={get:function(){return S.get.call(this)},set:function(e){_=""+e,S.set.call(this,e)}},A={eventTypes:P,extractEvents:function(e,t,r,o){var i,a;if(n(t)?N?i=s:a=u:O(t)?I?i=d:(i=h,a=f):m(t)&&(i=v),i){var c=i(e,t,r);if(c){var l=M.getPooled(P.change,c,o);return E.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,r)}};t.exports=A},{"./EventConstants":17,"./EventPluginHub":19,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactUpdates":88,"./SyntheticEvent":96,"./isEventSupported":138,"./isTextInputElement":140,"./keyOf":144}],9:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],10:[function(e,t){"use strict";function n(e){switch(e){case y.topCompositionStart:return E.compositionStart;case y.topCompositionEnd:return E.compositionEnd;case y.topCompositionUpdate:return E.compositionUpdate}}function r(e,t){return e===y.topKeyDown&&t.keyCode===h}function o(e,t){switch(e){case y.topKeyUp:return-1!==f.indexOf(t.keyCode);case y.topKeyDown:return t.keyCode!==h;case y.topKeyPress:case y.topMouseDown:case y.topBlur:return!0;default:return!1}}function i(e){this.root=e,this.startSelection=c.getSelection(e),this.startValue=this.getText()}var a=e("./EventConstants"),s=e("./EventPropagators"),u=e("./ExecutionEnvironment"),c=e("./ReactInputSelection"),l=e("./SyntheticCompositionEvent"),p=e("./getTextContentAccessor"),d=e("./keyOf"),f=[9,13,27,32],h=229,m=u.canUseDOM&&"CompositionEvent"in window,v=!m||"documentMode"in document&&document.documentMode>8&&document.documentMode<=11,y=a.topLevelTypes,g=null,E={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[y.topBlur,y.topCompositionEnd,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[y.topBlur,y.topCompositionStart,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[y.topBlur,y.topCompositionUpdate,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var e=this.getText(),t=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return e.substr(t,e.length-n-t)};var C={eventTypes:E,extractEvents:function(e,t,a,u){var c,p;if(m?c=n(e):g?o(e,u)&&(c=E.compositionEnd):r(e,u)&&(c=E.compositionStart),v&&(g||c!==E.compositionStart?c===E.compositionEnd&&g&&(p=g.getData(),g=null):g=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=C},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactInputSelection":63,"./SyntheticCompositionEvent":94,"./getTextContentAccessor":132,"./keyOf":144}],11:[function(e,t){"use strict";function n(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r,o=e("./Danger"),i=e("./ReactMultiChildUpdateTypes"),a=e("./getTextContentAccessor"),s=e("./invariant"),u=a();r="textContent"===u?function(e,t){e.textContent=t}:function(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);if(t){var n=e.ownerDocument||document;e.appendChild(n.createTextNode(t))}};var c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:r,processUpdates:function(e,t){for(var a,u=null,c=null,l=0;a=e[l];l++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var p=a.fromIndex,d=a.parentNode.childNodes[p],f=a.parentID;s(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,c=c||[],c.push(d)}var h=o.dangerouslyRenderMarkup(t);if(c)for(var m=0;m<c.length;m++)c[m].parentNode.removeChild(c[m]);for(var v=0;a=e[v];v++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,h[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,u[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:r(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};t.exports=c},{"./Danger":14,"./ReactMultiChildUpdateTypes":70,"./getTextContentAccessor":132,"./invariant":137}],12:[function(e,t){"use strict";function n(e,t){return(e&t)===t}var r=e("./invariant"),o={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},i=e.DOMAttributeNames||{},s=e.DOMPropertyNames||{},u=e.DOMMutationMethods||{};e.isCustomAttribute&&a._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var c in t){r(!a.isStandardName.hasOwnProperty(c)),a.isStandardName[c]=!0;var l=c.toLowerCase();if(a.getPossibleStandardName[l]=c,i.hasOwnProperty(c)){var p=i[c];a.getPossibleStandardName[p]=c,a.getAttributeName[c]=p}else a.getAttributeName[c]=l;a.getPropertyName[c]=s.hasOwnProperty(c)?s[c]:c,a.getMutationMethod[c]=u.hasOwnProperty(c)?u[c]:null;var d=t[c];a.mustUseAttribute[c]=n(d,o.MUST_USE_ATTRIBUTE),a.mustUseProperty[c]=n(d,o.MUST_USE_PROPERTY),a.hasSideEffects[c]=n(d,o.HAS_SIDE_EFFECTS),a.hasBooleanValue[c]=n(d,o.HAS_BOOLEAN_VALUE),a.hasNumericValue[c]=n(d,o.HAS_NUMERIC_VALUE),a.hasPositiveNumericValue[c]=n(d,o.HAS_POSITIVE_NUMERIC_VALUE),a.hasOverloadedBooleanValue[c]=n(d,o.HAS_OVERLOADED_BOOLEAN_VALUE),r(!a.mustUseAttribute[c]||!a.mustUseProperty[c]),r(a.mustUseProperty[c]||!a.hasSideEffects[c]),r(!!a.hasBooleanValue[c]+!!a.hasNumericValue[c]+!!a.hasOverloadedBooleanValue[c]<=1)}}},i={},a={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<a._isCustomAttributeFunctions.length;t++){var n=a._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=i[e];return r||(i[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:o};t.exports=a},{"./invariant":137}],13:[function(e,t){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e("./DOMProperty"),o=e("./escapeTextForBrowser"),i=e("./memoizeStringOnly"),a=(e("./warning"),i(function(e){return o(e)+'="'})),s={createMarkupForID:function(e){return a(r.ID_ATTRIBUTE_NAME)+o(e)+'"'},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var i=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?o(i):a(i)+o(t)+'"'}return r.isCustomAttribute(e)?null==t?"":a(e)+o(t)+'"':null},setValueForProperty:function(e,t,o){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var i=r.getMutationMethod[t];if(i)i(e,o);else if(n(t,o))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+o);else{var a=r.getPropertyName[t];r.hasSideEffects[t]&&""+e[a]==""+o||(e[a]=o)}}else r.isCustomAttribute(t)&&(null==o?e.removeAttribute(t):e.setAttribute(t,""+o))},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var o=r.getPropertyName[t],i=r.getDefaultValueForProperty(e.nodeName,o);r.hasSideEffects[t]&&""+e[o]===i||(e[o]=i)}}else r.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=s},{"./DOMProperty":12,"./escapeTextForBrowser":120,"./memoizeStringOnly":146,"./warning":155}],14:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e("./ExecutionEnvironment"),o=e("./createNodesFromMarkup"),i=e("./emptyFunction"),a=e("./getMarkupWrap"),s=e("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(e){s(r.canUseDOM);for(var t,l={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",l[t]=l[t]||[],l[t][p]=e[p];var d=[],f=0;for(t in l)if(l.hasOwnProperty(t)){var h=l[t];for(var m in h)if(h.hasOwnProperty(m)){var v=h[m];h[m]=v.replace(u,"$1 "+c+'="'+m+'" ')}var y=o(h.join(""),i);for(p=0;p<y.length;++p){var g=y[p];g.hasAttribute&&g.hasAttribute(c)&&(m=+g.getAttribute(c),g.removeAttribute(c),s(!d.hasOwnProperty(m)),d[m]=g,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(r.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=o(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=l},{"./ExecutionEnvironment":23,"./createNodesFromMarkup":114,"./emptyFunction":118,"./getMarkupWrap":129,"./invariant":137}],15:[function(e,t){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":144}],16:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./SyntheticMouseEvent"),i=e("./ReactMount"),a=e("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var m=f?i.getID(f):"",v=h?i.getID(h):"",y=o.getPooled(c.mouseLeave,m,a);y.type="mouseleave",y.target=f,y.relatedTarget=h;var g=o.getPooled(c.mouseEnter,v,a);return g.type="mouseenter",g.target=h,g.relatedTarget=f,r.accumulateEnterLeaveDispatches(y,g,m,v),l[0]=y,l[1]=g,l}};t.exports=p},{"./EventConstants":17,"./EventPropagators":22,"./ReactMount":68,"./SyntheticMouseEvent":100,"./keyOf":144}],17:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),o=n({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}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{"./keyMirror":143}],18:[function(e,t){var n=e("./emptyFunction"),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):{remove:n}},registerDefault:function(){}};t.exports=r},{"./emptyFunction":118}],19:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),r=e("./EventPluginUtils"),o=e("./accumulateInto"),i=e("./forEachAccumulated"),a=e("./invariant"),s={},u=null,c=function(e){if(e){var t=r.executeDispatch,o=n.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),r.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},l=null,p={injection:{injectMount:r.injection.injectMount,injectInstanceHandle:function(e){l=e},getInstanceHandle:function(){return l},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){a(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,r,i){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(e,t,r,i);p&&(a=o(a,p))}}return a},enqueueEvents:function(e){e&&(u=o(u,e))},processEventQueue:function(){var e=u;u=null,i(e,c),a(!u)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=p},{"./EventPluginRegistry":20,"./EventPluginUtils":21,"./accumulateInto":106,"./forEachAccumulated":123,"./invariant":137}],20:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var c in o)i(r(o[c],t,c))}}}function r(e,t,n){i(!u.eventNameDispatchConfigs.hasOwnProperty(n)),u.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var a in r)if(r.hasOwnProperty(a)){var s=r[a];o(s,t,n)}return!0}return e.registrationName?(o(e.registrationName,t,n),!0):!1}function o(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s.hasOwnProperty(r)&&s[r]===o||(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=u.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=u},{"./invariant":137}],21:[function(e,t){"use strict";function n(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function r(e){return e===m.topMouseMove||e===m.topTouchMove}function o(e){return e===m.topMouseDown||e===m.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){e.currentTarget=h.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;f(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e("./EventConstants"),f=e("./invariant"),h={Mount:null,injectMount:function(e){h.Mount=e}},m=d.topLevelTypes,v={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:l,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=v},{"./EventConstants":17,"./invariant":137}],22:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return m(e,r)}function r(e,t,r){var o=t?h.bubbled:h.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=m(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,o)}function u(e,t,n,r){p.injection.getInstanceHandle().traverseEnterLeave(n,r,i,e,t)}function c(e){f(e,a)}var l=e("./EventConstants"),p=e("./EventPluginHub"),d=e("./accumulateInto"),f=e("./forEachAccumulated"),h=l.PropagationPhases,m=p.getListener,v={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=v},{"./EventConstants":17,"./EventPluginHub":19,"./accumulateInto":106,"./forEachAccumulated":123}],23:[function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],24:[function(e,t){"use strict";var n,r=e("./DOMProperty"),o=e("./ExecutionEnvironment"),i=r.injection.MUST_USE_ATTRIBUTE,a=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,c=r.injection.HAS_NUMERIC_VALUE,l=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(o.canUseDOM){var d=document.implementation;n=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var f={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:i,checked:a|s,classID:i,className:n?i:a,cols:i|l,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:a|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:p,draggable:null,encType:null,form:i,formAction:i,formEncType:i,formMethod:i,formNoValidate:s,formTarget:i,frameBorder:i,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:i,loop:a|s,manifest:i,marginHeight:null,marginWidth:null,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,open:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:a|s,rel:null,required:s,role:i,rows:i|l,rowSpan:null,sandbox:null,scope:null,scrolling:null,seamless:i|s,selected:a|s,shape:null,size:i|l,sizes:i,span:l,spellCheck:null,src:null,srcDoc:a,srcSet:i,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:a|u,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|s,itemType:i,property:null},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=f},{"./DOMProperty":12,"./ExecutionEnvironment":23}],25:[function(e,t){"use strict";var n=e("./ReactLink"),r=e("./ReactStateSetters"),o={linkState:function(e){return new n(this.state[e],r.createStateKeySetter(this,e))}};t.exports=o},{"./ReactLink":66,"./ReactStateSetters":83}],26:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function o(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e("./ReactPropTypes"),u=e("./invariant"),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},l={Mixin:{propTypes:{value:function(e,t){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?void 0: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(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?void 0: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:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(o(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),i):e.props.checkedLink?(o(e),a):e.props.onChange}};t.exports=l},{"./ReactPropTypes":77,"./invariant":137}],27:[function(e,t){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),o=e("./accumulateInto"),i=e("./forEachAccumulated"),a=e("./invariant"),s={trapBubbledEvent:function(e,t){a(this.isMounted());var n=r.trapBubbledEvent(e,t,this.getDOMNode());this._localEventListeners=o(this._localEventListeners,n)},componentWillUnmount:function(){this._localEventListeners&&i(this._localEventListeners,n)}};t.exports=s},{"./ReactBrowserEventEmitter":33,"./accumulateInto":106,"./forEachAccumulated":123,"./invariant":137}],28:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{"./EventConstants":17,"./emptyFunction":118}],29:[function(e,t){function n(e){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var t=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(t[a]=i[a])}}return t}t.exports=n},{}],30:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},o=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},a=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,c=r,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:r,twoArgumentPooler:o,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{"./invariant":137}],31:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./EventPluginUtils"),o=e("./ReactChildren"),i=e("./ReactComponent"),a=e("./ReactCompositeComponent"),s=e("./ReactContext"),u=e("./ReactCurrentOwner"),c=e("./ReactElement"),l=(e("./ReactElementValidator"),e("./ReactDOM")),p=e("./ReactDOMComponent"),d=e("./ReactDefaultInjection"),f=e("./ReactInstanceHandles"),h=e("./ReactLegacyElement"),m=e("./ReactMount"),v=e("./ReactMultiChild"),y=e("./ReactPerf"),g=e("./ReactPropTypes"),E=e("./ReactServerRendering"),C=e("./ReactTextComponent"),R=e("./Object.assign"),M=e("./deprecated"),b=e("./onlyChild");
d.inject();var O=c.createElement,D=c.createFactory;O=h.wrapCreateElement(O),D=h.wrapCreateFactory(D);var x=y.measure("React","render",m.render),P={Children:{map:o.map,forEach:o.forEach,count:o.count,only:b},DOM:l,PropTypes:g,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createElement:O,createFactory:D,constructAndRenderComponent:m.constructAndRenderComponent,constructAndRenderComponentByID:m.constructAndRenderComponentByID,render:x,renderToString:E.renderToString,renderToStaticMarkup:E.renderToStaticMarkup,unmountComponentAtNode:m.unmountComponentAtNode,isValidClass:h.isValidClass,isValidElement:c.isValidElement,withContext:s.withContext,__spread:R,renderComponent:M("React","renderComponent","render",this,x),renderComponentToString:M("React","renderComponentToString","renderToString",this,E.renderToString),renderComponentToStaticMarkup:M("React","renderComponentToStaticMarkup","renderToStaticMarkup",this,E.renderToStaticMarkup),isValidComponent:M("React","isValidComponent","isValidElement",this,c.isValidElement)};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({Component:i,CurrentOwner:u,DOMComponent:p,DOMPropertyOperations:n,InstanceHandles:f,Mount:m,MultiChild:v,TextComponent:C});P.version="0.12.2",t.exports=P},{"./DOMPropertyOperations":13,"./EventPluginUtils":21,"./Object.assign":29,"./ReactChildren":36,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactDOM":43,"./ReactDOMComponent":45,"./ReactDefaultInjection":55,"./ReactElement":56,"./ReactElementValidator":57,"./ReactInstanceHandles":64,"./ReactLegacyElement":65,"./ReactMount":68,"./ReactMultiChild":69,"./ReactPerf":73,"./ReactPropTypes":77,"./ReactServerRendering":81,"./ReactTextComponent":84,"./deprecated":117,"./onlyChild":148}],32:[function(e,t){"use strict";var n=e("./ReactEmptyComponent"),r=e("./ReactMount"),o=e("./invariant"),i={getDOMNode:function(){return o(this.isMounted()),n.isNullComponentID(this._rootNodeID)?null:r.getNode(this._rootNodeID)}};t.exports=i},{"./ReactEmptyComponent":58,"./ReactMount":68,"./invariant":137}],33:[function(e,t){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=d++,l[e[h]]={}),l[e[h]]}var r=e("./EventConstants"),o=e("./EventPluginHub"),i=e("./EventPluginRegistry"),a=e("./ReactEventEmitterMixin"),s=e("./ViewportMetrics"),u=e("./Object.assign"),c=e("./isEventSupported"),l={},p=!1,d=0,f={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"},h="_reactListenersID"+String(Math.random()).slice(2),m=u({},a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!m.ReactEventListener||!m.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],u=r.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];a.hasOwnProperty(d)&&a[d]||(d===u.topWheel?c("wheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",o):c("mousewheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",o):m.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",o):d===u.topScroll?c("scroll",!0)?m.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",o):m.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",m.ReactEventListener.WINDOW_HANDLE):d===u.topFocus||d===u.topBlur?(c("focus",!0)?(m.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",o),m.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",o)):c("focusin")&&(m.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",o),m.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",o)),a[u.topBlur]=!0,a[u.topFocus]=!0):f.hasOwnProperty(d)&&m.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),p=!0}},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:o.putListener,getListener:o.getListener,deleteListener:o.deleteListener,deleteAllListeners:o.deleteAllListeners});t.exports=m},{"./EventConstants":17,"./EventPluginHub":19,"./EventPluginRegistry":20,"./Object.assign":29,"./ReactEventEmitterMixin":60,"./ViewportMetrics":105,"./isEventSupported":138}],34:[function(e,t){"use strict";var n=e("./React"),r=e("./Object.assign"),o=n.createFactory(e("./ReactTransitionGroup")),i=n.createFactory(e("./ReactCSSTransitionGroupChild")),a=n.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:n.PropTypes.string.isRequired,transitionEnter:n.PropTypes.bool,transitionLeave:n.PropTypes.bool},getDefaultProps:function(){return{transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return i({name:this.props.transitionName,enter:this.props.transitionEnter,leave:this.props.transitionLeave},e)},render:function(){return o(r({},this.props,{childFactory:this._wrapChild}))}});t.exports=a},{"./Object.assign":29,"./React":31,"./ReactCSSTransitionGroupChild":35,"./ReactTransitionGroup":87}],35:[function(e,t){"use strict";var n=e("./React"),r=e("./CSSCore"),o=e("./ReactTransitionEvents"),i=e("./onlyChild"),a=17,s=n.createClass({displayName:"ReactCSSTransitionGroupChild",transition:function(e,t){var n=this.getDOMNode(),i=this.props.name+"-"+e,a=i+"-active",s=function(e){e&&e.target!==n||(r.removeClass(n,i),r.removeClass(n,a),o.removeEndEventListener(n,s),t&&t())};o.addEndEventListener(n,s),r.addClass(n,i),this.queueClass(a)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,a))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(r.addClass.bind(r,this.getDOMNode())),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillEnter:function(e){this.props.enter?this.transition("enter",e):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e):e()},render:function(){return i(this.props.children)}});t.exports=s},{"./CSSCore":4,"./React":31,"./ReactTransitionEvents":86,"./onlyChild":148}],36:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function o(e,t,o){if(null==e)return e;var i=n.getPooled(t,o);p(e,r,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function s(e,t,n){if(null==e)return e;var r={},o=i.getPooled(r,t,n);return p(e,a,o),i.release(o),r}function u(){return null}function c(e){return p(e,u,null)}var l=e("./PooledClass"),p=e("./traverseAllChildren"),d=(e("./warning"),l.twoArgumentPooler),f=l.threeArgumentPooler;l.addPoolingTo(n,d),l.addPoolingTo(i,f);var h={forEach:o,map:s,count:c};t.exports=h},{"./PooledClass":30,"./traverseAllChildren":153,"./warning":155}],37:[function(e,t){"use strict";var n=e("./ReactElement"),r=e("./ReactOwner"),o=e("./ReactUpdates"),i=e("./Object.assign"),a=e("./invariant"),s=e("./keyMirror"),u=s({MOUNTED:null,UNMOUNTED:null}),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){a(!c),p=e.mountImageIntoNode,l=e.unmountIDFromEnvironment,d.BackendIDOperations=e.BackendIDOperations,c=!0}},LifeCycle:u,BackendIDOperations:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(e,t){var n=this._pendingElement||this._currentElement;this.replaceProps(i({},n.props,e),t)},replaceProps:function(e,t){a(this.isMounted()),a(0===this._mountDepth),this._pendingElement=n.cloneAndReplaceProps(this._pendingElement||this._currentElement,e),o.enqueueUpdate(this,t)},_setPropsInternal:function(e,t){var r=this._pendingElement||this._currentElement;this._pendingElement=n.cloneAndReplaceProps(r,i({},r.props,e)),o.enqueueUpdate(this,t)},construct:function(e){this.props=e.props,this._owner=e._owner,this._lifeCycleState=u.UNMOUNTED,this._pendingCallbacks=null,this._currentElement=e,this._pendingElement=null},mountComponent:function(e,t,n){a(!this.isMounted());var o=this._currentElement.ref;if(null!=o){var i=this._currentElement._owner;r.addComponentAsRefTo(this,o,i)}this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){a(this.isMounted());var e=this._currentElement.ref;null!=e&&r.removeComponentAsRefFrom(this,e,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){a(this.isMounted()),this._pendingElement=e,this.performUpdateIfNecessary(t)},performUpdateIfNecessary:function(e){if(null!=this._pendingElement){var t=this._currentElement,n=this._pendingElement;this._currentElement=n,this.props=n.props,this._owner=n._owner,this._pendingElement=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this._currentElement;(n._owner!==t._owner||n.ref!==t.ref)&&(null!=t.ref&&r.removeComponentAsRefFrom(this,t.ref,t._owner),null!=n.ref&&r.addComponentAsRefTo(this,n.ref,n._owner))},mountComponentIntoNode:function(e,t,n){var r=o.ReactReconcileTransaction.getPooled();r.perform(this._mountComponentIntoNode,this,e,t,r,n),o.ReactReconcileTransaction.release(r)},_mountComponentIntoNode:function(e,t,n,r){var o=this.mountComponent(e,n,0);p(o,t,r)},isOwnedBy:function(e){return this._owner===e},getSiblingByRef:function(e){var t=this._owner;return t&&t.refs?t.refs[e]:null}}};t.exports=d},{"./Object.assign":29,"./ReactElement":56,"./ReactOwner":72,"./ReactUpdates":88,"./invariant":137,"./keyMirror":143}],38:[function(e,t){"use strict";var n=e("./ReactDOMIDOperations"),r=e("./ReactMarkupChecksum"),o=e("./ReactMount"),i=e("./ReactPerf"),a=e("./ReactReconcileTransaction"),s=e("./getReactRootElementInContainer"),u=e("./invariant"),c=e("./setInnerHTML"),l=1,p=9,d={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(e){o.purgeID(e)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(e,t,n){if(u(t&&(t.nodeType===l||t.nodeType===p)),n){if(r.canReuseMarkup(e,s(t)))return;u(t.nodeType!==p)}u(t.nodeType!==p),c(t,e)})};t.exports=d},{"./ReactDOMIDOperations":47,"./ReactMarkupChecksum":67,"./ReactMount":68,"./ReactPerf":73,"./ReactReconcileTransaction":79,"./getReactRootElementInContainer":131,"./invariant":137,"./setInnerHTML":149}],39:[function(e,t){"use strict";var n=e("./shallowEqual"),r={shouldComponentUpdate:function(e,t){return!n(this.props,e)||!n(this.state,t)}};t.exports=r},{"./shallowEqual":150}],40:[function(e,t){"use strict";function n(e){var t=e._owner||null;return t&&t.constructor&&t.constructor.displayName?" Check the render method of `"+t.constructor.displayName+"`.":""}function r(e,t){for(var n in t)t.hasOwnProperty(n)&&D("function"==typeof t[n])}function o(e,t){var n=I.hasOwnProperty(t)?I[t]:null;L.hasOwnProperty(t)&&D(n===S.OVERRIDE_BASE),e.hasOwnProperty(t)&&D(n===S.DEFINE_MANY||n===S.DEFINE_MANY_MERGED)}function i(e){var t=e._compositeLifeCycleState;D(e.isMounted()||t===A.MOUNTING),D(null==f.current),D(t!==A.UNMOUNTING)}function a(e,t){if(t){D(!y.isValidFactory(t)),D(!h.isValidElement(t));var n=e.prototype;t.hasOwnProperty(_)&&k.mixins(e,t.mixins);for(var r in t)if(t.hasOwnProperty(r)&&r!==_){var i=t[r];if(o(n,r),k.hasOwnProperty(r))k[r](e,i);else{var a=I.hasOwnProperty(r),s=n.hasOwnProperty(r),u=i&&i.__reactDontBind,p="function"==typeof i,d=p&&!a&&!s&&!u;if(d)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[r]=i,n[r]=i;else if(s){var f=I[r];D(a&&(f===S.DEFINE_MANY_MERGED||f===S.DEFINE_MANY)),f===S.DEFINE_MANY_MERGED?n[r]=c(n[r],i):f===S.DEFINE_MANY&&(n[r]=l(n[r],i))}else n[r]=i}}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in k;D(!o);var i=n in e;D(!i),e[n]=r}}}function u(e,t){return D(e&&t&&"object"==typeof e&&"object"==typeof t),T(t,function(t,n){D(void 0===e[n]),e[n]=t}),e}function c(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);return null==n?r:null==r?n:u(n,r)}}function l(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}var p=e("./ReactComponent"),d=e("./ReactContext"),f=e("./ReactCurrentOwner"),h=e("./ReactElement"),m=(e("./ReactElementValidator"),e("./ReactEmptyComponent")),v=e("./ReactErrorUtils"),y=e("./ReactLegacyElement"),g=e("./ReactOwner"),E=e("./ReactPerf"),C=e("./ReactPropTransferer"),R=e("./ReactPropTypeLocations"),M=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),b=e("./Object.assign"),O=e("./instantiateReactComponent"),D=e("./invariant"),x=e("./keyMirror"),P=e("./keyOf"),T=(e("./monitorCodeUse"),e("./mapObject")),w=e("./shouldUpdateReactComponent"),_=(e("./warning"),P({mixins:null})),S=x({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),N=[],I={mixins:S.DEFINE_MANY,statics:S.DEFINE_MANY,propTypes:S.DEFINE_MANY,contextTypes:S.DEFINE_MANY,childContextTypes:S.DEFINE_MANY,getDefaultProps:S.DEFINE_MANY_MERGED,getInitialState:S.DEFINE_MANY_MERGED,getChildContext:S.DEFINE_MANY_MERGED,render:S.DEFINE_ONCE,componentWillMount:S.DEFINE_MANY,componentDidMount:S.DEFINE_MANY,componentWillReceiveProps:S.DEFINE_MANY,shouldComponentUpdate:S.DEFINE_ONCE,componentWillUpdate:S.DEFINE_MANY,componentDidUpdate:S.DEFINE_MANY,componentWillUnmount:S.DEFINE_MANY,updateComponent:S.OVERRIDE_BASE},k={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)a(e,t[n])},childContextTypes:function(e,t){r(e,t,R.childContext),e.childContextTypes=b({},e.childContextTypes,t)},contextTypes:function(e,t){r(e,t,R.context),e.contextTypes=b({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?c(e.getDefaultProps,t):t},propTypes:function(e,t){r(e,t,R.prop),e.propTypes=b({},e.propTypes,t)},statics:function(e,t){s(e,t)}},A=x({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null}),L={construct:function(){p.Mixin.construct.apply(this,arguments),g.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._compositeLifeCycleState=null},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==A.MOUNTING},mountComponent:E.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=A.MOUNTING,this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.context=this._processContext(this._currentElement._context),this.props=this._processProps(this.props),this.state=this.getInitialState?this.getInitialState():null,D("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=O(this._renderValidatedComponent(),this._currentElement.type),this._compositeLifeCycleState=null;var r=this._renderedComponent.mountComponent(e,t,n+1);return this.componentDidMount&&t.getReactMountReady().enqueue(this.componentDidMount,this),r}),unmountComponent:function(){this._compositeLifeCycleState=A.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(e,t){D("object"==typeof e||null==e),this.replaceState(b({},this._pendingState||this.state,e),t)},replaceState:function(e,t){i(this),this._pendingState=e,this._compositeLifeCycleState!==A.MOUNTING&&M.enqueueUpdate(this,t)},_processContext:function(e){var t=null,n=this.constructor.contextTypes;if(n){t={};for(var r in n)t[r]=e[r]}return t},_processChildContext:function(e){var t=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",t){D("object"==typeof this.constructor.childContextTypes);for(var n in t)D(n in this.constructor.childContextTypes);return b({},e,t)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,r){var o=this.constructor.displayName;for(var i in e)if(e.hasOwnProperty(i)){var a=e[i](t,i,o,r);a instanceof Error&&n(this)}},performUpdateIfNecessary:function(e){var t=this._compositeLifeCycleState;if(t!==A.MOUNTING&&t!==A.RECEIVING_PROPS&&(null!=this._pendingElement||null!=this._pendingState||this._pendingForceUpdate)){var n=this.context,r=this.props,o=this._currentElement;null!=this._pendingElement&&(o=this._pendingElement,n=this._processContext(o._context),r=this._processProps(o.props),this._pendingElement=null,this._compositeLifeCycleState=A.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(r,n)),this._compositeLifeCycleState=null;var i=this._pendingState||this.state;this._pendingState=null;var a=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(r,i,n);a?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,n,e)):(this._currentElement=o,this.props=r,this.state=i,this.context=n,this._owner=o._owner)}},_performComponentUpdate:function(e,t,n,r,o){var i=this._currentElement,a=this.props,s=this.state,u=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this._currentElement=e,this.props=t,this.state=n,this.context=r,this._owner=e._owner,this.updateComponent(o,i),this.componentDidUpdate&&o.getReactMountReady().enqueue(this.componentDidUpdate.bind(this,a,s,u),this)},receiveComponent:function(e,t){(e!==this._currentElement||null==e._owner)&&p.Mixin.receiveComponent.call(this,e,t)},updateComponent:E.measure("ReactCompositeComponent","updateComponent",function(e,t){p.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(w(r,o))n.receiveComponent(o,e);else{var i=this._rootNodeID,a=n._rootNodeID;n.unmountComponent(),this._renderedComponent=O(o,this._currentElement.type);var s=this._renderedComponent.mountComponent(i,e,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(e){var t=this._compositeLifeCycleState;D(this.isMounted()||t===A.MOUNTING),D(t!==A.UNMOUNTING&&null==f.current),this._pendingForceUpdate=!0,M.enqueueUpdate(this,e)},_renderValidatedComponent:E.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._currentElement._context),f.current=this;try{e=this.render(),null===e||e===!1?(e=m.getEmptyComponent(),m.registerNullComponentID(this._rootNodeID)):m.deregisterNullComponentID(this._rootNodeID)}finally{d.current=t,f.current=null}return D(h.isValidElement(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(v.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=e.bind(t);return n}},U=function(){};b(U.prototype,p.Mixin,g.Mixin,C.Mixin,L);var F={LifeCycle:A,Base:U,createClass:function(e){var t=function(){};t.prototype=new U,t.prototype.constructor=t,N.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),D(t.prototype.render);for(var n in I)t.prototype[n]||(t.prototype[n]=null);return y.wrapFactory(h.createFactory(t))},injection:{injectMixin:function(e){N.push(e)}}};t.exports=F},{"./Object.assign":29,"./ReactComponent":37,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactElementValidator":57,"./ReactEmptyComponent":58,"./ReactErrorUtils":59,"./ReactLegacyElement":65,"./ReactOwner":72,"./ReactPerf":73,"./ReactPropTransferer":74,"./ReactPropTypeLocationNames":75,"./ReactPropTypeLocations":76,"./ReactUpdates":88,"./instantiateReactComponent":136,"./invariant":137,"./keyMirror":143,"./keyOf":144,"./mapObject":145,"./monitorCodeUse":147,"./shouldUpdateReactComponent":151,"./warning":155}],41:[function(e,t){"use strict";var n=e("./Object.assign"),r={current:{},withContext:function(e,t){var o,i=r.current;r.current=n({},i,e);try{o=t()}finally{r.current=i}return o}};t.exports=r},{"./Object.assign":29}],42:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],43:[function(e,t){"use strict";function n(e){return o.markNonLegacyFactory(r.createFactory(e))}var r=e("./ReactElement"),o=(e("./ReactElementValidator"),e("./ReactLegacyElement")),i=e("./mapObject"),a=i({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",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"},n);t.exports=a},{"./ReactElement":56,"./ReactElementValidator":57,"./ReactLegacyElement":65,"./mapObject":145}],44:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),i=e("./ReactElement"),a=e("./ReactDOM"),s=e("./keyMirror"),u=i.createFactory(a.button.type),c=s({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),l=o.createClass({displayName:"ReactDOMButton",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&c[t]||(e[t]=this.props[t]);return u(e,this.props.children)}});t.exports=l},{"./AutoFocusMixin":2,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./keyMirror":143}],45:[function(e,t){"use strict";function n(e){e&&(y(null==e.children||null==e.dangerouslySetInnerHTML),y(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=d.findReactContainerForID(e);if(o){var i=o.nodeType===O?o.ownerDocument:o;C(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e){T.call(P,e)||(y(x.test(e)),P[e]=!0)}function i(e){o(e),this._tag=e,this.tagName=e.toUpperCase()}var a=e("./CSSPropertyOperations"),s=e("./DOMProperty"),u=e("./DOMPropertyOperations"),c=e("./ReactBrowserComponentMixin"),l=e("./ReactComponent"),p=e("./ReactBrowserEventEmitter"),d=e("./ReactMount"),f=e("./ReactMultiChild"),h=e("./ReactPerf"),m=e("./Object.assign"),v=e("./escapeTextForBrowser"),y=e("./invariant"),g=(e("./isEventSupported"),e("./keyOf")),E=(e("./monitorCodeUse"),p.deleteListener),C=p.listenTo,R=p.registrationNameModules,M={string:!0,number:!0},b=g({style:null}),O=1,D={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},x=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,P={},T={}.hasOwnProperty;i.displayName="ReactDOMComponent",i.Mixin={mountComponent:h.measure("ReactDOMComponent","mountComponent",function(e,t,r){l.Mixin.mountComponent.call(this,e,t,r),n(this.props);var o=D[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+o}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n="<"+this._tag;for(var o in t)if(t.hasOwnProperty(o)){var i=t[o];if(null!=i)if(R.hasOwnProperty(o))r(this._rootNodeID,o,i,e);else{o===b&&(i&&(i=t.style=m({},t.style)),i=a.createMarkupForStyles(i));var s=u.createMarkupForProperty(o,i);s&&(n+=" "+s)}}if(e.renderToStaticMarkup)return n+">";var c=u.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=M[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return v(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._currentElement||null==e._owner)&&l.Mixin.receiveComponent.call(this,e,t)},updateComponent:h.measure("ReactDOMComponent","updateComponent",function(e,t){n(this._currentElement.props),l.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,o,i,a=this.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===b){var u=e[n];for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else R.hasOwnProperty(n)?E(this._rootNodeID,n):(s.isStandardName[n]||s.isCustomAttribute(n))&&l.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in a){var c=a[n],p=e[n];if(a.hasOwnProperty(n)&&c!==p)if(n===b)if(c&&(c=a.style=m({},c)),p){for(o in p)!p.hasOwnProperty(o)||c&&c.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in c)c.hasOwnProperty(o)&&p[o]!==c[o]&&(i=i||{},i[o]=c[o])}else i=c;else R.hasOwnProperty(n)?r(this._rootNodeID,n,c,t):(s.isStandardName[n]||s.isCustomAttribute(n))&&l.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,c)}i&&l.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t){var n=this.props,r=M[typeof e.children]?e.children:null,o=M[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,u=null!=o?null:n.children,c=null!=r||null!=i,p=null!=o||null!=a;null!=s&&null==u?this.updateChildren(null,t):c&&!p&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&l.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),p.deleteAllListeners(this._rootNodeID),l.Mixin.unmountComponent.call(this)}},m(i.prototype,l.Mixin,i.Mixin,f.Mixin,c),t.exports=i},{"./CSSPropertyOperations":6,"./DOMProperty":12,"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactMount":68,"./ReactMultiChild":69,"./ReactPerf":73,"./escapeTextForBrowser":120,"./invariant":137,"./isEventSupported":138,"./keyOf":144,"./monitorCodeUse":147}],46:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactElement"),s=e("./ReactDOM"),u=a.createFactory(s.form.type),c=i.createClass({displayName:"ReactDOMForm",mixins:[o,r],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=c},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56}],47:[function(e,t){"use strict";var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),o=e("./DOMPropertyOperations"),i=e("./ReactMount"),a=e("./ReactPerf"),s=e("./invariant"),u=e("./setInnerHTML"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:a.measure("ReactDOMIDOperations","updatePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)}),deletePropertyByID:a.measure("ReactDOMIDOperations","deletePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)}),updateStylesByID:a.measure("ReactDOMIDOperations","updateStylesByID",function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)}),updateInnerHTMLByID:a.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(e,t){var n=i.getNode(e);u(n,t)}),updateTextContentByID:a.measure("ReactDOMIDOperations","updateTextContentByID",function(e,t){var n=i.getNode(e);r.updateTextContent(n,t)}),dangerouslyReplaceNodeWithMarkupByID:a.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)}),dangerouslyProcessChildrenUpdates:a.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)})};t.exports=l},{"./CSSPropertyOperations":6,"./DOMChildrenOperations":11,"./DOMPropertyOperations":13,"./ReactMount":68,"./ReactPerf":73,"./invariant":137,"./setInnerHTML":149}],48:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactElement"),s=e("./ReactDOM"),u=a.createFactory(s.img.type),c=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=c},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56}],49:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactElement"),c=e("./ReactDOM"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=e("./invariant"),h=u.createFactory(c.input.type),m={},v=s.createClass({displayName:"ReactDOMInput",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue;
return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=i.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=i.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,h(e,this.props.children)},componentDidMount:function(){var e=l.getID(this.getDOMNode());m[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=l.getID(e);delete m[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&o.setValueForProperty(e,"checked",this.props.checked||!1);var t=i.getValue(this);null!=t&&o.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,r=i.getOnChange(this);r&&(t=r.call(this,e)),p.asap(n,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var a=this.getDOMNode(),s=a;s.parentNode;)s=s.parentNode;for(var u=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),c=0,d=u.length;d>c;c++){var h=u[c];if(h!==a&&h.form===a.form){var v=l.getID(h);f(v);var y=m[v];f(y),p.asap(n,y)}}}return t}});t.exports=v},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactMount":68,"./ReactUpdates":88,"./invariant":137}],50:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),o=e("./ReactElement"),i=e("./ReactDOM"),a=(e("./warning"),o.createFactory(i.option.type)),s=r.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return a(this.props,this.props.children)}});t.exports=s},{"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./warning":155}],51:[function(e,t){"use strict";function n(){this.isMounted()&&(this.setState({value:this._pendingValue}),this._pendingValue=0)}function r(e,t){if(null!=e[t])if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function o(e,t){var n,r,o,i=e.props.multiple,a=null!=t?t:e.state.value,s=e.getDOMNode().options;if(i)for(n={},r=0,o=a.length;o>r;++r)n[""+a[r]]=!0;else n=""+a;for(r=0,o=s.length;o>r;r++){var u=i?n.hasOwnProperty(s[r].value):s[r].value===n;u!==s[r].selected&&(s[r].selected=u)}}var i=e("./AutoFocusMixin"),a=e("./LinkedValueUtils"),s=e("./ReactBrowserComponentMixin"),u=e("./ReactCompositeComponent"),c=e("./ReactElement"),l=e("./ReactDOM"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=c.createFactory(l.select.type),h=u.createClass({displayName:"ReactDOMSelect",mixins:[i,a.Mixin,s],propTypes:{defaultValue:r,value:r},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillMount:function(){this._pendingValue=null},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,f(e,this.props.children)},componentDidMount:function(){o(this,a.getValue(this))},componentDidUpdate:function(e){var t=a.getValue(this),n=!!e.multiple,r=!!this.props.multiple;(null!=t||n!==r)&&o(this,t)},_handleChange:function(e){var t,r=a.getOnChange(this);r&&(t=r.call(this,e));var o;if(this.props.multiple){o=[];for(var i=e.target.options,s=0,u=i.length;u>s;s++)i[s].selected&&o.push(i[s].value)}else o=e.target.value;return this._pendingValue=o,p.asap(n,this),t}});t.exports=h},{"./AutoFocusMixin":2,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactUpdates":88}],52:[function(e,t){"use strict";function n(e,t,n,r){return e===n&&t===r}function r(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function o(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var r=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,l=s.cloneRange();l.selectNodeContents(e),l.setEnd(s.startContainer,s.startOffset);var p=n(l.startContainer,l.startOffset,l.endContainer,l.endOffset),d=p?0:l.toString().length,f=d+c,h=document.createRange();h.setStart(r,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function a(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=u(e,o),l=u(e,i);if(s&&l){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p))}}}var s=e("./ExecutionEnvironment"),u=e("./getNodeForCharacterOffset"),c=e("./getTextContentAccessor"),l=s.canUseDOM&&document.selection,p={getOffsets:l?r:o,setOffsets:l?i:a};t.exports=p},{"./ExecutionEnvironment":23,"./getNodeForCharacterOffset":130,"./getTextContentAccessor":132}],53:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactElement"),c=e("./ReactDOM"),l=e("./ReactUpdates"),p=e("./Object.assign"),d=e("./invariant"),f=(e("./warning"),u.createFactory(c.textarea.type)),h=s.createClass({displayName:"ReactDOMTextarea",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(d(null==e),Array.isArray(t)&&(d(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=i.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,f(e,this.state.initialValue)},componentDidUpdate:function(){var e=i.getValue(this);if(null!=e){var t=this.getDOMNode();o.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,r=i.getOnChange(this);return r&&(t=r.call(this,e)),l.asap(n,this),t}});t.exports=h},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactUpdates":88,"./invariant":137,"./warning":155}],54:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),o=e("./Transaction"),i=e("./Object.assign"),a=e("./emptyFunction"),s={initialize:a,close:function(){p.isBatchingUpdates=!1}},u={initialize:a,close:r.flushBatchedUpdates.bind(r)},c=[u,s];i(n.prototype,o.Mixin,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n){var r=p.isBatchingUpdates;p.isBatchingUpdates=!0,r?e(t,n):l.perform(e,null,t,n)}};t.exports=p},{"./Object.assign":29,"./ReactUpdates":88,"./Transaction":104,"./emptyFunction":118}],55:[function(e,t){"use strict";function n(){O.EventEmitter.injectReactEventListener(b),O.EventPluginHub.injectEventPluginOrder(s),O.EventPluginHub.injectInstanceHandle(D),O.EventPluginHub.injectMount(x),O.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:w,EnterLeaveEventPlugin:u,ChangeEventPlugin:o,CompositionEventPlugin:a,MobileSafariClickEventPlugin:p,SelectEventPlugin:P,BeforeInputEventPlugin:r}),O.NativeComponent.injectGenericComponentClass(m),O.NativeComponent.injectComponentClasses({button:v,form:y,img:g,input:E,option:C,select:R,textarea:M,html:S("html"),head:S("head"),body:S("body")}),O.CompositeComponent.injectMixin(d),O.DOMProperty.injectDOMPropertyConfig(l),O.DOMProperty.injectDOMPropertyConfig(_),O.EmptyComponent.injectEmptyComponent("noscript"),O.Updates.injectReconcileTransaction(f.ReactReconcileTransaction),O.Updates.injectBatchingStrategy(h),O.RootIndex.injectCreateReactRootIndex(c.canUseDOM?i.createReactRootIndex:T.createReactRootIndex),O.Component.injectEnvironment(f)}var r=e("./BeforeInputEventPlugin"),o=e("./ChangeEventPlugin"),i=e("./ClientReactRootIndex"),a=e("./CompositionEventPlugin"),s=e("./DefaultEventPluginOrder"),u=e("./EnterLeaveEventPlugin"),c=e("./ExecutionEnvironment"),l=e("./HTMLDOMPropertyConfig"),p=e("./MobileSafariClickEventPlugin"),d=e("./ReactBrowserComponentMixin"),f=e("./ReactComponentBrowserEnvironment"),h=e("./ReactDefaultBatchingStrategy"),m=e("./ReactDOMComponent"),v=e("./ReactDOMButton"),y=e("./ReactDOMForm"),g=e("./ReactDOMImg"),E=e("./ReactDOMInput"),C=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),b=e("./ReactEventListener"),O=e("./ReactInjection"),D=e("./ReactInstanceHandles"),x=e("./ReactMount"),P=e("./SelectEventPlugin"),T=e("./ServerReactRootIndex"),w=e("./SimpleEventPlugin"),_=e("./SVGDOMPropertyConfig"),S=e("./createFullPageComponent");t.exports={inject:n}},{"./BeforeInputEventPlugin":3,"./ChangeEventPlugin":8,"./ClientReactRootIndex":9,"./CompositionEventPlugin":10,"./DefaultEventPluginOrder":15,"./EnterLeaveEventPlugin":16,"./ExecutionEnvironment":23,"./HTMLDOMPropertyConfig":24,"./MobileSafariClickEventPlugin":28,"./ReactBrowserComponentMixin":32,"./ReactComponentBrowserEnvironment":38,"./ReactDOMButton":44,"./ReactDOMComponent":45,"./ReactDOMForm":46,"./ReactDOMImg":48,"./ReactDOMInput":49,"./ReactDOMOption":50,"./ReactDOMSelect":51,"./ReactDOMTextarea":53,"./ReactDefaultBatchingStrategy":54,"./ReactEventListener":61,"./ReactInjection":62,"./ReactInstanceHandles":64,"./ReactMount":68,"./SVGDOMPropertyConfig":89,"./SelectEventPlugin":90,"./ServerReactRootIndex":91,"./SimpleEventPlugin":92,"./createFullPageComponent":113}],56:[function(e,t){"use strict";var n=e("./ReactContext"),r=e("./ReactCurrentOwner"),o=(e("./warning"),{key:!0,ref:!0}),i=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=o,this.props=i};i.prototype={_isReactElement:!0},i.createElement=function(e,t,a){var s,u={},c=null,l=null;if(null!=t){l=void 0===t.ref?null:t.ref,c=null==t.key?null:""+t.key;for(s in t)t.hasOwnProperty(s)&&!o.hasOwnProperty(s)&&(u[s]=t[s])}var p=arguments.length-2;if(1===p)u.children=a;else if(p>1){for(var d=Array(p),f=0;p>f;f++)d[f]=arguments[f+2];u.children=d}if(e&&e.defaultProps){var h=e.defaultProps;for(s in h)"undefined"==typeof u[s]&&(u[s]=h[s])}return new i(e,c,l,r.current,n.current,u)},i.createFactory=function(e){var t=i.createElement.bind(null,e);return t.type=e,t},i.cloneAndReplaceProps=function(e,t){var n=new i(e.type,e.key,e.ref,e._owner,e._context,t);return n},i.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=i},{"./ReactContext":41,"./ReactCurrentOwner":42,"./warning":155}],57:[function(e,t){"use strict";function n(){var e=p.current;return e&&e.constructor.displayName||void 0}function r(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,i("react_key_warning",'Each child in an array should have a unique "key" prop.',e,t))}function o(e,t,n){v.test(e)&&i("react_numeric_key_warning","Child objects should have non-numeric keys so ordering is preserved.",t,n)}function i(e,t,r,o){var i=n(),a=o.displayName,s=i||a,u=f[e];if(!u.hasOwnProperty(s)){u[s]=!0,t+=i?" Check the render method of "+i+".":" Check the renderComponent call using <"+a+">.";var c=null;r._owner&&r._owner!==p.current&&(c=r._owner.constructor.displayName,t+=" It was passed a child from "+c+"."),t+=" See http://fb.me/react-warning-keys for more information.",d(e,{component:s,componentOwner:c}),console.warn(t)}}function a(){var e=n()||"";h.hasOwnProperty(e)||(h[e]=!0,d("react_object_map_children"))}function s(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var i=e[n];c.isValidElement(i)&&r(i,t)}else if(c.isValidElement(e))e._store.validated=!0;else if(e&&"object"==typeof e){a();for(var s in e)o(s,e[s],t)}}function u(e,t,n,r){for(var o in t)if(t.hasOwnProperty(o)){var i;try{i=t[o](n,o,e,r)}catch(a){i=a}i instanceof Error&&!(i.message in m)&&(m[i.message]=!0,d("react_failed_descriptor_type_check",{message:i.message}))}}var c=e("./ReactElement"),l=e("./ReactPropTypeLocations"),p=e("./ReactCurrentOwner"),d=e("./monitorCodeUse"),f=(e("./warning"),{react_key_warning:{},react_numeric_key_warning:{}}),h={},m={},v=/^\d+$/,y={createElement:function(e){var t=c.createElement.apply(this,arguments);if(null==t)return t;for(var n=2;n<arguments.length;n++)s(arguments[n],e);if(e){var r=e.displayName;e.propTypes&&u(r,e.propTypes,t.props,l.prop),e.contextTypes&&u(r,e.contextTypes,t._context,l.context)}return t},createFactory:function(e){var t=y.createElement.bind(null,e);return t.type=e,t}};t.exports=y},{"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactPropTypeLocations":76,"./monitorCodeUse":147,"./warning":155}],58:[function(e,t){"use strict";function n(){return u(a),a()}function r(e){c[e]=!0}function o(e){delete c[e]}function i(e){return c[e]}var a,s=e("./ReactElement"),u=e("./invariant"),c={},l={injectEmptyComponent:function(e){a=s.createFactory(e)}},p={deregisterNullComponentID:o,getEmptyComponent:n,injection:l,isNullComponentID:i,registerNullComponentID:r};t.exports=p},{"./ReactElement":56,"./invariant":137}],59:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],60:[function(e,t){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e("./EventPluginHub"),o={handleTopLevel:function(e,t,o,i){var a=r.extractEvents(e,t,o,i);n(a)}};t.exports=o},{"./EventPluginHub":19}],61:[function(e,t){"use strict";function n(e){var t=l.getID(e),n=c.getReactRootIDFromNodeID(t),r=l.findReactContainerForID(n),o=l.getFirstReactDOM(r);return o}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){for(var t=l.getFirstReactDOM(f(e.nativeEvent))||window,r=t;r;)e.ancestors.push(r),r=n(r);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=l.getID(t)||"";m._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=h(window);e(t)}var a=e("./EventListener"),s=e("./ExecutionEnvironment"),u=e("./PooledClass"),c=e("./ReactInstanceHandles"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=e("./getEventTarget"),h=e("./getUnboundedScrollPosition");d(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var m={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){m._handleTopLevel=e},setEnabled:function(e){m._enabled=!!e},isEnabled:function(){return m._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,m.dispatchEvent.bind(null,e)):void 0},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,m.dispatchEvent.bind(null,e)):void 0},monitorScrollValue:function(e){var t=i.bind(null,e);a.listen(window,"scroll",t),a.listen(window,"resize",t)},dispatchEvent:function(e,t){if(m._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=m},{"./EventListener":18,"./ExecutionEnvironment":23,"./Object.assign":29,"./PooledClass":30,"./ReactInstanceHandles":64,"./ReactMount":68,"./ReactUpdates":88,"./getEventTarget":128,"./getUnboundedScrollPosition":133}],62:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),o=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactEmptyComponent"),s=e("./ReactBrowserEventEmitter"),u=e("./ReactNativeComponent"),c=e("./ReactPerf"),l=e("./ReactRootIndex"),p=e("./ReactUpdates"),d={Component:o.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EmptyComponent:a.injection,EventPluginHub:r.injection,EventEmitter:s.injection,NativeComponent:u.injection,Perf:c.injection,RootIndex:l.injection,Updates:p.injection};t.exports=d},{"./DOMProperty":12,"./EventPluginHub":19,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactEmptyComponent":58,"./ReactNativeComponent":71,"./ReactPerf":73,"./ReactRootIndex":80,"./ReactUpdates":88}],63:[function(e,t){"use strict";function n(e){return o(document.documentElement,e)}var r=e("./ReactDOMSelection"),o=e("./containsNode"),i=e("./focusNode"),a=e("./getActiveElement"),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),r=e.focusedElem,o=e.selectionRange;t!==r&&n(r)&&(s.hasSelectionCapabilities(r)&&s.setSelection(r,o),i(r))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};t.exports=s},{"./ReactDOMSelection":52,"./containsNode":111,"./focusNode":122,"./getActiveElement":124}],64:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function r(e,t){return e.charAt(t)===d||t===e.length}function o(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(o(e)&&o(t)),p(i(e,t)),e===t)return e;for(var n=e.length+f,a=n;a<t.length&&!r(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(o(s)),s}function c(e,t,n,r,o,u){e=e||"",t=t||"",p(e!==t);var c=i(t,e);p(c||i(e,t));for(var l=0,d=c?a:s,f=e;;f=d(f,t)){var m;if(o&&f===e||u&&f===t||(m=n(f,c,r)),m===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,m={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=m},{"./ReactRootIndex":80,"./invariant":137}],65:[function(e,t){"use strict";function n(e,t){if("function"==typeof t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];if("function"==typeof r){var o=r.bind(t);for(var i in r)r.hasOwnProperty(i)&&(o[i]=r[i]);e[n]=o}else e[n]=r}}var r=(e("./ReactCurrentOwner"),e("./invariant")),o=(e("./monitorCodeUse"),e("./warning"),{}),i={},a={};a.wrapCreateFactory=function(e){var t=function(t){return"function"!=typeof t?e(t):t.isReactNonLegacyFactory?e(t.type):t.isReactLegacyFactory?e(t.type):t};return t},a.wrapCreateElement=function(e){var t=function(t){if("function"!=typeof t)return e.apply(this,arguments);var n;return t.isReactNonLegacyFactory?(n=Array.prototype.slice.call(arguments,0),n[0]=t.type,e.apply(this,n)):t.isReactLegacyFactory?(t._isMockFunction&&(t.type._mockedReactClassConstructor=t),n=Array.prototype.slice.call(arguments,0),n[0]=t.type,e.apply(this,n)):t.apply(null,Array.prototype.slice.call(arguments,1))};return t},a.wrapFactory=function(e){r("function"==typeof e);var t=function(){return e.apply(this,arguments)};return n(t,e.type),t.isReactLegacyFactory=o,t.type=e.type,t},a.markNonLegacyFactory=function(e){return e.isReactNonLegacyFactory=i,e},a.isValidFactory=function(e){return"function"==typeof e&&e.isReactLegacyFactory===o},a.isValidClass=function(e){return a.isValidFactory(e)},a._isLegacyCallWarningEnabled=!0,t.exports=a},{"./ReactCurrentOwner":42,"./invariant":137,"./monitorCodeUse":147,"./warning":155}],66:[function(e,t){"use strict";function n(e,t){this.value=e,this.requestChange=t}function r(e){var t={value:"undefined"==typeof e?o.PropTypes.any.isRequired:e.isRequired,requestChange:o.PropTypes.func.isRequired};return o.PropTypes.shape(t)}var o=e("./React");n.PropTypes={link:r},t.exports=n},{"./React":31}],67:[function(e,t){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{"./adler32":107}],68:[function(e,t){"use strict";function n(e){var t=E(e);return t&&I.getID(t)}function r(e){var t=o(e);if(t)if(x.hasOwnProperty(t)){var n=x[t];n!==e&&(R(!s(n,t)),x[t]=e)}else x[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(D)||""}function i(e,t){var n=o(e);n!==t&&delete x[n],e.setAttribute(D,t),x[t]=e}function a(e){return x.hasOwnProperty(e)&&s(x[e],e)||(x[e]=I.findReactNodeByID(e)),x[e]}function s(e,t){if(e){R(o(e)===t);var n=I.findReactContainerForID(t);if(n&&y(n,e))return!0}return!1}function u(e){delete x[e]}function c(e){var t=x[e];return t&&s(t,e)?void(N=t):!1}function l(e){N=null,m.traverseAncestors(e,c);var t=N;return N=null,t}var p=e("./DOMProperty"),d=e("./ReactBrowserEventEmitter"),f=(e("./ReactCurrentOwner"),e("./ReactElement")),h=e("./ReactLegacyElement"),m=e("./ReactInstanceHandles"),v=e("./ReactPerf"),y=e("./containsNode"),g=e("./deprecated"),E=e("./getReactRootElementInContainer"),C=e("./instantiateReactComponent"),R=e("./invariant"),M=e("./shouldUpdateReactComponent"),b=(e("./warning"),h.wrapCreateElement(f.createElement)),O=m.SEPARATOR,D=p.ID_ATTRIBUTE_NAME,x={},P=1,T=9,w={},_={},S=[],N=null,I={_instancesByReactRootID:w,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){var o=t.props;return I.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){R(t&&(t.nodeType===P||t.nodeType===T)),d.ensureScrollValueMonitoring();var n=I.registerContainer(t);return w[n]=e,n},_renderNewRootComponent:v.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var r=C(e,null),o=I._registerComponent(r,t);return r.mountComponentIntoNode(o,t,n),r}),render:function(e,t,r){R(f.isValidElement(e));var o=w[n(t)];if(o){var i=o._currentElement;if(M(i,e))return I._updateRootComponent(o,e,t,r);I.unmountComponentAtNode(t)}var a=E(t),s=a&&I.isRenderedByReact(a),u=s&&!o,c=I._renderNewRootComponent(e,t,u);return r&&r.call(c),c},constructAndRenderComponent:function(e,t,n){var r=b(e,t);return I.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return R(r),I.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=n(e);return t&&(t=m.getReactRootIDFromNodeID(t)),t||(t=m.createReactRootID()),_[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),r=w[t];return r?(I.unmountComponentFromNode(r,e),delete w[t],delete _[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===T&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=m.getReactRootIDFromNodeID(e),n=_[t];return n},findReactNodeByID:function(e){var t=I.findReactContainerForID(e);return I.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=I.getID(e);return t?t.charAt(0)===O:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(I.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=S,r=0,o=l(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=I.getID(a);s?t===s?i=a:m.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,R(!1)},getReactRootID:n,getID:r,setID:i,getNode:a,purgeID:u};I.renderComponent=g("ReactMount","renderComponent","render",this,I.render),t.exports=I},{"./DOMProperty":12,"./ReactBrowserEventEmitter":33,"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactInstanceHandles":64,"./ReactLegacyElement":65,"./ReactPerf":73,"./containsNode":111,"./deprecated":117,"./getReactRootElementInContainer":131,"./instantiateReactComponent":136,"./invariant":137,"./shouldUpdateReactComponent":151,"./warning":155}],69:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function o(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){h.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(h,m),s())}function s(){h.length=0,m.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t){var n=l(e),r=[],o=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a,null);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,t,this._mountDepth+1);s._mountIndex=o,r.push(c),o++}}return r},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():a())}},updateChildren:function(e,t){f++;var n=!0;try{this._updateChildren(e,t),n=!1}finally{f--,f||(n?s():a())}},_updateChildren:function(e,t){var n=l(e),r=this._renderedChildren;if(n||r){var o,i=0,a=0;for(o in n)if(n.hasOwnProperty(o)){var s=r&&r[o],u=s&&s._currentElement,c=n[o];if(d(u,c))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(c,t),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,o));var f=p(c,null);this._mountChildByNameAtIndex(f,o,a,t)}a++}for(o in r)!r.hasOwnProperty(o)||n&&n[o]||this._unmountChildByName(r[o],o)}},unmountChildren:function(){var e=this._renderedChildren;for(var t in e){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){o(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r){var o=this._rootNodeID+t,i=e.mountComponent(o,r,this._mountDepth+1);e._mountIndex=n,this.createChild(e,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[t]=e},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null,e.unmountComponent(),delete this._renderedChildren[t]}}};t.exports=v},{"./ReactComponent":37,"./ReactMultiChildUpdateTypes":70,"./flattenChildren":121,"./instantiateReactComponent":136,"./shouldUpdateReactComponent":151}],70:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{"./keyMirror":143}],71:[function(e,t){"use strict";function n(e,t,n){var r=a[e];return null==r?(o(i),new i(e,t)):n===e?(o(i),new i(e,t)):new r.type(t)}var r=e("./Object.assign"),o=e("./invariant"),i=null,a={},s={injectGenericComponentClass:function(e){i=e},injectComponentClasses:function(e){r(a,e)}},u={createInstanceForTag:n,injection:s};t.exports=u},{"./Object.assign":29,"./invariant":137}],72:[function(e,t){"use strict";var n=e("./emptyObject"),r=e("./invariant"),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.refs[t]===e&&n.detachRef(t)},Mixin:{construct:function(){this.refs=n},attachRef:function(e,t){r(t.isOwnedBy(this));var o=this.refs===n?this.refs={}:this.refs;o[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=o},{"./emptyObject":119,"./invariant":137}],73:[function(e,t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measure:function(e,t,n){return n},injection:{injectMeasure:function(e){r.storedMeasure=e}}};t.exports=r},{}],74:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}function r(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=c[n];r&&c.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var o=e("./Object.assign"),i=e("./emptyFunction"),a=e("./invariant"),s=e("./joinClasses"),u=(e("./warning"),n(function(e,t){return o({},t,e)})),c={children:i,className:n(s),style:u},l={TransferStrategies:c,mergeProps:function(e,t){return r(o({},e),t)},Mixin:{transferPropsTo:function(e){return a(e._owner===this),r(e.props,this.props),e}}};t.exports=l},{"./Object.assign":29,"./emptyFunction":118,"./invariant":137,"./joinClasses":142,"./warning":155}],75:[function(e,t){"use strict";var n={};t.exports=n},{}],76:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":143}],77:[function(e,t){"use strict";function n(e){function t(t,n,r,o,i){if(o=o||C,null!=n[r])return e(n,r,o,i);var a=y[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):void 0}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,r,o){var i=t[n],a=h(i);if(a!==e){var s=y[o],u=m(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}}return n(t)}function o(){return n(E.thatReturns())}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=y[o],s=h(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function a(){function e(e,t,n,r){if(!v.isValidElement(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=y[o],a=e.name||C;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}}return n(t)}function u(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return;var s=y[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return n(t)}function c(e){function t(t,n,r,o){var i=t[n],a=h(i);
if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var u in i)if(i.hasOwnProperty(u)){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function l(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return}var s=y[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return n(t)}function p(){function e(e,t,n,r){if(!f(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var l=c(i,u,r,o);if(l)return l}}}return n(t,"expected `object`")}function f(e){switch(typeof e){case"number":case"string":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(f);if(v.isValidElement(e))return!0;for(var t in e)if(!f(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var v=e("./ReactElement"),y=e("./ReactPropTypeLocationNames"),g=e("./deprecated"),E=e("./emptyFunction"),C="<<anonymous>>",R=a(),M=p(),b={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,element:R,instanceOf:s,node:M,objectOf:c,oneOf:u,oneOfType:l,shape:d,component:g("React.PropTypes","component","element",this,R),renderable:g("React.PropTypes","renderable","node",this,M)};t.exports=b},{"./ReactElement":56,"./ReactPropTypeLocationNames":75,"./deprecated":117,"./emptyFunction":118}],78:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),o=e("./ReactBrowserEventEmitter"),i=e("./Object.assign");i(n.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];o.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33}],79:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e("./CallbackQueue"),o=e("./PooledClass"),i=e("./ReactBrowserEventEmitter"),a=e("./ReactInputSelection"),s=e("./ReactPutListenerQueue"),u=e("./Transaction"),c=e("./Object.assign"),l={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,l,p,d],m={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n.prototype,u.Mixin,m),o.addPoolingTo(n),t.exports=n},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33,"./ReactInputSelection":63,"./ReactPutListenerQueue":78,"./Transaction":104}],80:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],81:[function(e,t){"use strict";function n(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=u(e,null),o=r.mountComponent(n,t,0);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=u(e,null);return r.mountComponent(n,t,0)},null)}finally{s.release(t)}}var o=e("./ReactElement"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderToString:n,renderToStaticMarkup:r}},{"./ReactElement":56,"./ReactInstanceHandles":64,"./ReactMarkupChecksum":67,"./ReactServerRenderingTransaction":82,"./instantiateReactComponent":136,"./invariant":137}],82:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=o.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e("./PooledClass"),o=e("./CallbackQueue"),i=e("./ReactPutListenerQueue"),a=e("./Transaction"),s=e("./Object.assign"),u=e("./emptyFunction"),c={initialize:function(){this.reactMountReady.reset()},close:u},l={initialize:function(){this.putListenerQueue.reset()},close:u},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};s(n.prototype,a.Mixin,d),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactPutListenerQueue":78,"./Transaction":104,"./emptyFunction":118}],83:[function(e,t){"use strict";function n(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var r={createStateSetter:function(e,t){return function(n,r,o,i,a,s){var u=t.call(e,n,r,o,i,a,s);u&&e.setState(u)}},createStateKeySetter:function(e,t){var r=e.__keySetters||(e.__keySetters={});return r[t]||(r[t]=n(e,t))}};r.Mixin={createStateSetter:function(e){return r.createStateSetter(this,e)},createStateKeySetter:function(e){return r.createStateKeySetter(this,e)}},t.exports=r},{}],84:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactComponent"),o=e("./ReactElement"),i=e("./Object.assign"),a=e("./escapeTextForBrowser"),s=function(){};i(s.prototype,r.Mixin,{mountComponent:function(e,t,o){r.Mixin.mountComponent.call(this,e,t,o);var i=a(this.props);return t.renderToStaticMarkup?i:"<span "+n.createMarkupForID(e)+">"+i+"</span>"},receiveComponent:function(e){var t=e.props;t!==this.props&&(this.props=t,r.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}});var u=function(e){return new o(s,null,null,null,null,e)};u.type=s,t.exports=u},{"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactComponent":37,"./ReactElement":56,"./escapeTextForBrowser":120}],85:[function(e,t){"use strict";var n=e("./ReactChildren"),r={getChildMapping:function(e){return n.map(e,function(e){return e})},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var i in e)t.hasOwnProperty(i)?o.length&&(r[i]=o,o=[]):o.push(i);var a,s={};for(var u in t){if(r.hasOwnProperty(u))for(a=0;a<r[u].length;a++){var c=r[u][a];s[r[u][a]]=n(c)}s[u]=n(u)}for(a=0;a<o.length;a++)s[o[a]]=n(o[a]);return s}};t.exports=r},{"./ReactChildren":36}],86:[function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a){var r=a[n];for(var o in r)if(o in t){s.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}var i=e("./ExecutionEnvironment"),a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[];i.canUseDOM&&n();var u={addEndEventListener:function(e,t){return 0===s.length?void window.setTimeout(t,0):void s.forEach(function(n){r(e,n,t)})},removeEndEventListener:function(e,t){0!==s.length&&s.forEach(function(n){o(e,n,t)})}};t.exports=u},{"./ExecutionEnvironment":23}],87:[function(e,t){"use strict";var n=e("./React"),r=e("./ReactTransitionChildMapping"),o=e("./Object.assign"),i=e("./cloneWithProps"),a=e("./emptyFunction"),s=n.createClass({displayName:"ReactTransitionGroup",propTypes:{component:n.PropTypes.any,childFactory:n.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:a.thatReturnsArgument}},getInitialState:function(){return{children:r.getChildMapping(this.props.children)}},componentWillReceiveProps:function(e){var t=r.getChildMapping(e.children),n=this.state.children;this.setState({children:r.mergeChildMappings(n,t)});var o;for(o in t){var i=n&&n.hasOwnProperty(o);!t[o]||i||this.currentlyTransitioningKeys[o]||this.keysToEnter.push(o)}for(o in n){var a=t&&t.hasOwnProperty(o);!n[o]||a||this.currentlyTransitioningKeys[o]||this.keysToLeave.push(o)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);if(n&&n.hasOwnProperty(e))this.performEnter(e);else{var i=o({},this.state.children);delete i[e],this.setState({children:i})}},render:function(){var e={};for(var t in this.state.children){var r=this.state.children[t];r&&(e[t]=i(this.props.childFactory(r),{ref:t}))}return n.createElement(this.props.component,this.props,e)}});t.exports=s},{"./Object.assign":29,"./React":31,"./ReactTransitionChildMapping":85,"./cloneWithProps":110,"./emptyFunction":118}],88:[function(e,t){"use strict";function n(){h(O.ReactReconcileTransaction&&g)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=O.ReactReconcileTransaction.getPooled()}function o(e,t,r){n(),g.batchedUpdates(e,t,r)}function i(e,t){return e._mountDepth-t._mountDepth}function a(e){var t=e.dirtyComponentsLength;h(t===m.length),m.sort(i);for(var n=0;t>n;n++){var r=m[n];if(r.isMounted()){var o=r._pendingCallbacks;if(r._pendingCallbacks=null,r.performUpdateIfNecessary(e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r)}}}function s(e,t){return h(!t||"function"==typeof t),n(),g.isBatchingUpdates?(m.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):void g.batchedUpdates(s,e,t)}function u(e,t){h(g.isBatchingUpdates),v.enqueue(e,t),y=!0}var c=e("./CallbackQueue"),l=e("./PooledClass"),p=(e("./ReactCurrentOwner"),e("./ReactPerf")),d=e("./Transaction"),f=e("./Object.assign"),h=e("./invariant"),m=(e("./warning"),[]),v=c.getPooled(),y=!1,g=null,E={initialize:function(){this.dirtyComponentsLength=m.length},close:function(){this.dirtyComponentsLength!==m.length?(m.splice(0,this.dirtyComponentsLength),M()):m.length=0}},C={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},R=[E,C];f(r.prototype,d.Mixin,{getTransactionWrappers:function(){return R},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,O.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return d.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),l.addPoolingTo(r);var M=p.measure("ReactUpdates","flushBatchedUpdates",function(){for(;m.length||y;){if(m.length){var e=r.getPooled();e.perform(a,null,e),r.release(e)}if(y){y=!1;var t=v;v=c.getPooled(),t.notifyAll(),c.release(t)}}}),b={injectReconcileTransaction:function(e){h(e),O.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){h(e),h("function"==typeof e.batchedUpdates),h("boolean"==typeof e.isBatchingUpdates),g=e}},O={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:M,injection:b,asap:u};t.exports=O},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactCurrentOwner":42,"./ReactPerf":73,"./Transaction":104,"./invariant":137,"./warning":155}],89:[function(e,t){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,o={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},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"}};t.exports=o},{"./DOMProperty":12}],90:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function r(e){if(!y&&null!=h&&h==u()){var t=n(h);if(!v||!p(v,t)){v=t;var r=s.getPooled(f.select,m,e);return r.type="select",r.target=h,i.accumulateTwoPhaseDispatches(r),r}}}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ReactInputSelection"),s=e("./SyntheticEvent"),u=e("./getActiveElement"),c=e("./isTextInputElement"),l=e("./keyOf"),p=e("./shallowEqual"),d=o.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,m=null,v=null,y=!1,g={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,m=n,v=null);break;case d.topBlur:h=null,m=null,v=null;break;case d.topMouseDown:y=!0;break;case d.topContextMenu:case d.topMouseUp:return y=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=g},{"./EventConstants":17,"./EventPropagators":22,"./ReactInputSelection":63,"./SyntheticEvent":96,"./getActiveElement":124,"./isTextInputElement":140,"./keyOf":144,"./shallowEqual":150}],91:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],92:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPluginUtils"),o=e("./EventPropagators"),i=e("./SyntheticClipboardEvent"),a=e("./SyntheticEvent"),s=e("./SyntheticFocusEvent"),u=e("./SyntheticKeyboardEvent"),c=e("./SyntheticMouseEvent"),l=e("./SyntheticDragEvent"),p=e("./SyntheticTouchEvent"),d=e("./SyntheticUIEvent"),f=e("./SyntheticWheelEvent"),h=e("./getEventCharCode"),m=e("./invariant"),v=e("./keyOf"),y=(e("./warning"),n.topLevelTypes),g={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},E={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel};for(var C in E)E[C].dependencies=[C];var R={eventTypes:g,executeDispatch:function(e,t,n){var o=r.executeDispatch(e,t,n);o===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=E[e];if(!v)return null;var g;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:g=a;break;case y.topKeyPress:if(0===h(r))return null;case y.topKeyDown:case y.topKeyUp:g=u;break;case y.topBlur:case y.topFocus:g=s;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:g=c;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:g=l;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:g=p;break;case y.topScroll:g=d;break;case y.topWheel:g=f;break;case y.topCopy:case y.topCut:case y.topPaste:g=i}m(g);var C=g.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(C),C}};t.exports=R},{"./EventConstants":17,"./EventPluginUtils":21,"./EventPropagators":22,"./SyntheticClipboardEvent":93,"./SyntheticDragEvent":95,"./SyntheticEvent":96,"./SyntheticFocusEvent":97,"./SyntheticKeyboardEvent":99,"./SyntheticMouseEvent":100,"./SyntheticTouchEvent":101,"./SyntheticUIEvent":102,"./SyntheticWheelEvent":103,"./getEventCharCode":125,"./invariant":137,"./keyOf":144,"./warning":155}],93:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],94:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],95:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={dataTransfer:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":100}],96:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var a=r[o];this[o]=a?a(n):n[o]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?i.thatReturnsTrue:i.thatReturnsFalse,this.isPropagationStopped=i.thatReturnsFalse}var r=e("./PooledClass"),o=e("./Object.assign"),i=e("./emptyFunction"),a=e("./getEventTarget"),s={type:null,target:a,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=i.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=i.thatReturnsTrue},persist:function(){this.isPersistent=i.thatReturnsTrue},isPersistent:i.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=s,n.augmentClass=function(e,t){var n=this,i=Object.create(n.prototype);o(i,e.prototype),e.prototype=i,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./emptyFunction":118,"./getEventTarget":128}],97:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":102}],98:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],99:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventCharCode"),i=e("./getEventKey"),a=e("./getEventModifierState"),s={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:a,charCode:function(e){return"keypress"===e.type?o(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?o(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(n,s),t.exports=n},{"./SyntheticUIEvent":102,"./getEventCharCode":125,"./getEventKey":126,"./getEventModifierState":127}],100:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),i=e("./getEventModifierState"),a={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":102,"./ViewportMetrics":105,"./getEventModifierState":127}],101:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventModifierState"),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":102,"./getEventModifierState":127}],102:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o=e("./getEventTarget"),i={view:function(e){if(e.view)return e.view;var t=o(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,i),t.exports=n},{"./SyntheticEvent":96,"./getEventTarget":128}],103:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":100}],104:[function(e,t){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,r,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var i,a=t[r],s=this.wrapperInitData[r];try{i=!0,s!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o},{"./invariant":137}],105:[function(e,t){"use strict";var n=e("./getUnboundedScrollPosition"),r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var e=n(window);r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{"./getUnboundedScrollPosition":133}],106:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n&&o?(e.push.apply(e,t),e):n?(e.push(t),e):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":137}],107:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],108:[function(e,t){function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;t.exports=n},{}],109:[function(e,t){"use strict";function n(e){return r(e.replace(o,"ms-"))}var r=e("./camelize"),o=/^-ms-/;t.exports=n},{"./camelize":108}],110:[function(e,t){"use strict";function n(e,t){var n=o.mergeProps(t,e.props);return!n.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(n.children=e.props.children),r.createElement(e.type,n)}var r=e("./ReactElement"),o=e("./ReactPropTransferer"),i=e("./keyOf"),a=(e("./warning"),i({children:null}));t.exports=n},{"./ReactElement":56,"./ReactPropTransferer":74,"./keyOf":144,"./warning":155}],111:[function(e,t){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e("./isTextNode");t.exports=n},{"./isTextNode":141}],112:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():o(e):[e]}var o=e("./toArray");t.exports=r},{"./toArray":152}],113:[function(e,t){"use strict";function n(e){var t=o.createFactory(e),n=r.createClass({displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){i(!1)},render:function(){return t(this.props)}});return n}var r=e("./ReactCompositeComponent"),o=e("./ReactElement"),i=e("./invariant");t.exports=n},{"./ReactCompositeComponent":40,"./ReactElement":56,"./invariant":137}],114:[function(e,t){function n(e){var t=e.match(c);return t&&t[1].toLowerCase()}function r(e,t){var r=u;s(!!u);var o=n(e),c=o&&a(o);if(c){r.innerHTML=c[1]+e+c[2];for(var l=c[0];l--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return d}var o=e("./ExecutionEnvironment"),i=e("./createArrayFrom"),a=e("./getMarkupWrap"),s=e("./invariant"),u=o.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=r},{"./ExecutionEnvironment":23,"./createArrayFrom":112,"./getMarkupWrap":129,"./invariant":137}],115:[function(e,t){function n(e){return"object"==typeof e?Object.keys(e).filter(function(t){return e[t]}).join(" "):Array.prototype.join.call(arguments," ")}t.exports=n},{}],116:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.hasOwnProperty(e)&&o[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")
}var r=e("./CSSProperty"),o=r.isUnitlessNumber;t.exports=n},{"./CSSProperty":5}],117:[function(e,t){function n(e,t,n,r,o){return o}e("./Object.assign"),e("./warning");t.exports=n},{"./Object.assign":29,"./warning":155}],118:[function(e,t){function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},t.exports=r},{}],119:[function(e,t){"use strict";var n={};t.exports=n},{}],120:[function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;t.exports=r},{}],121:[function(e,t){"use strict";function n(e,t,n){var r=e,i=!r.hasOwnProperty(n);if(i&&null!=t){var a,s=typeof t;a="string"===s?o(t):"number"===s?o(""+t):t,r[n]=a}}function r(e){if(null==e)return e;var t={};return i(e,n,t),t}{var o=e("./ReactTextComponent"),i=e("./traverseAllChildren");e("./warning")}t.exports=r},{"./ReactTextComponent":84,"./traverseAllChildren":153,"./warning":155}],122:[function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}t.exports=n},{}],123:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],124:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],125:[function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=n},{}],126:[function(e,t){"use strict";function n(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=r(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":""}var r=e("./getEventCharCode"),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={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"};t.exports=n},{"./getEventCharCode":125}],127:[function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=r},{}],128:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],129:[function(e,t){function n(e){return o(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var r=e("./ExecutionEnvironment"),o=e("./invariant"),i=r.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[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:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,ellipse:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};t.exports=n},{"./ExecutionEnvironment":23,"./invariant":137}],130:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3==o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}t.exports=o},{}],131:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],132:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var r=e("./ExecutionEnvironment"),o=null;t.exports=n},{"./ExecutionEnvironment":23}],133:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],134:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],135:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e("./hyphenate"),o=/^ms-/;t.exports=n},{"./hyphenate":134}],136:[function(e,t){"use strict";function n(e,t){var n;return n="string"==typeof e.type?r.createInstanceForTag(e.type,e.props,t):new e.type(e.props),n.construct(e),n}{var r=(e("./warning"),e("./ReactElement"),e("./ReactLegacyElement"),e("./ReactNativeComponent"));e("./ReactEmptyComponent")}t.exports=n},{"./ReactElement":56,"./ReactEmptyComponent":58,"./ReactLegacyElement":65,"./ReactNativeComponent":71,"./warning":155}],137:[function(e,t){"use strict";var n=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};t.exports=n},{}],138:[function(e,t){"use strict";function n(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var r,o=e("./ExecutionEnvironment");o.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":23}],139:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],140:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],141:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":139}],142:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e=(e?e+" ":"")+t);return e}t.exports=n},{}],143:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{"./invariant":137}],144:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],145:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o={};for(var i in e)r.call(e,i)&&(o[i]=t.call(n,e[i],i,e));return o}var r=Object.prototype.hasOwnProperty;t.exports=n},{}],146:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],147:[function(e,t){"use strict";function n(e){r(e&&!/[^a-z0-9_]/.test(e))}var r=e("./invariant");t.exports=n},{"./invariant":137}],148:[function(e,t){"use strict";function n(e){return o(r.isValidElement(e)),e}var r=e("./ReactElement"),o=e("./invariant");t.exports=n},{"./ReactElement":56,"./invariant":137}],149:[function(e,t){"use strict";var n=e("./ExecutionEnvironment"),r=/^[ \r\n\t\f]/,o=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,i=function(e,t){e.innerHTML=t};if(n.canUseDOM){var a=document.createElement("div");a.innerHTML=" ",""===a.innerHTML&&(i=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&o.test(t)){e.innerHTML=""+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=i},{"./ExecutionEnvironment":23}],150:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],151:[function(e,t){"use strict";function n(e,t){return e&&t&&e.type===t.type&&e.key===t.key&&e._owner===t._owner?!0:!1}t.exports=n},{}],152:[function(e,t){function n(e){var t=e.length;if(r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),r("number"==typeof t),r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var o=Array(t),i=0;t>i;i++)o[i]=e[i];return o}var r=e("./invariant");t.exports=n},{"./invariant":137}],153:[function(e,t){"use strict";function n(e){return d[e]}function r(e,t){return e&&null!=e.key?i(e.key):t.toString(36)}function o(e){return(""+e).replace(f,n)}function i(e){return"$"+o(e)}function a(e,t,n){return null==e?0:h(e,"",0,t,n)}var s=e("./ReactElement"),u=e("./ReactInstanceHandles"),c=e("./invariant"),l=u.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,o,a){var u,d,f=0;if(Array.isArray(e))for(var m=0;m<e.length;m++){var v=e[m];u=t+(t?p:l)+r(v,m),d=n+f,f+=h(v,u,d,o,a)}else{var y=typeof e,g=""===t,E=g?l+r(e,0):t;if(null==e||"boolean"===y)o(a,null,E,n),f=1;else if("string"===y||"number"===y||s.isValidElement(e))o(a,e,E,n),f=1;else if("object"===y){c(!e||1!==e.nodeType);for(var C in e)e.hasOwnProperty(C)&&(u=t+(t?p:l)+i(C)+p+r(e[C],0),d=n+f,f+=h(e[C],u,d,o,a))}}return f};t.exports=a},{"./ReactElement":56,"./ReactInstanceHandles":64,"./invariant":137}],154:[function(e,t){"use strict";function n(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?i(new e.constructor,e):e}function r(e,t,n){s(Array.isArray(e));var r=t[n];s(Array.isArray(r))}function o(e,t){if(s("object"==typeof t),t.hasOwnProperty(p))return s(1===Object.keys(t).length),t[p];var a=n(e);if(t.hasOwnProperty(d)){var h=t[d];s(h&&"object"==typeof h),s(a&&"object"==typeof a),i(a,t[d])}t.hasOwnProperty(u)&&(r(e,t,u),t[u].forEach(function(e){a.push(e)})),t.hasOwnProperty(c)&&(r(e,t,c),t[c].forEach(function(e){a.unshift(e)})),t.hasOwnProperty(l)&&(s(Array.isArray(e)),s(Array.isArray(t[l])),t[l].forEach(function(e){s(Array.isArray(e)),a.splice.apply(a,e)})),t.hasOwnProperty(f)&&(s("function"==typeof t[f]),a=t[f](a));for(var v in t)m.hasOwnProperty(v)&&m[v]||(a[v]=o(e[v],t[v]));return a}var i=e("./Object.assign"),a=e("./keyOf"),s=e("./invariant"),u=a({$push:null}),c=a({$unshift:null}),l=a({$splice:null}),p=a({$set:null}),d=a({$merge:null}),f=a({$apply:null}),h=[u,c,l,p,d,f],m={};h.forEach(function(e){m[e]=!0}),t.exports=o},{"./Object.assign":29,"./invariant":137,"./keyOf":144}],155:[function(e,t){"use strict";var n=e("./emptyFunction"),r=n;t.exports=r},{"./emptyFunction":118}]},{},[1])(1)}); |
ajax/libs/oojs-ui/0.19.2/oojs-ui.js | froala/cdnjs | /*!
* OOjs UI v0.19.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-02-14T22:47:20Z
*/
( function ( OO ) {
'use strict';
/**
* Namespace for all classes, static methods and static properties.
*
* @class
* @singleton
*/
OO.ui = {};
OO.ui.bind = $.proxy;
/**
* @property {Object}
*/
OO.ui.Keys = {
UNDEFINED: 0,
BACKSPACE: 8,
DELETE: 46,
LEFT: 37,
RIGHT: 39,
UP: 38,
DOWN: 40,
ENTER: 13,
END: 35,
HOME: 36,
TAB: 9,
PAGEUP: 33,
PAGEDOWN: 34,
ESCAPE: 27,
SHIFT: 16,
SPACE: 32
};
/**
* Constants for MouseEvent.which
*
* @property {Object}
*/
OO.ui.MouseButtons = {
LEFT: 1,
MIDDLE: 2,
RIGHT: 3
};
/**
* @property {number}
* @private
*/
OO.ui.elementId = 0;
/**
* Generate a unique ID for element
*
* @return {string} ID
*/
OO.ui.generateElementId = function () {
OO.ui.elementId++;
return 'oojsui-' + OO.ui.elementId;
};
/**
* Check if an element is focusable.
* Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
*
* @param {jQuery} $element Element to test
* @return {boolean}
*/
OO.ui.isFocusableElement = function ( $element ) {
var nodeName,
element = $element[ 0 ];
// Anything disabled is not focusable
if ( element.disabled ) {
return false;
}
// Check if the element is visible
if ( !(
// This is quicker than calling $element.is( ':visible' )
$.expr.filters.visible( element ) &&
// Check that all parents are visible
!$element.parents().addBack().filter( function () {
return $.css( this, 'visibility' ) === 'hidden';
} ).length
) ) {
return false;
}
// Check if the element is ContentEditable, which is the string 'true'
if ( element.contentEditable === 'true' ) {
return true;
}
// Anything with a non-negative numeric tabIndex is focusable.
// Use .prop to avoid browser bugs
if ( $element.prop( 'tabIndex' ) >= 0 ) {
return true;
}
// Some element types are naturally focusable
// (indexOf is much faster than regex in Chrome and about the
// same in FF: https://jsperf.com/regex-vs-indexof-array2)
nodeName = element.nodeName.toLowerCase();
if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
return true;
}
// Links and areas are focusable if they have an href
if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
return true;
}
return false;
};
/**
* Find a focusable child
*
* @param {jQuery} $container Container to search in
* @param {boolean} [backwards] Search backwards
* @return {jQuery} Focusable child, an empty jQuery object if none found
*/
OO.ui.findFocusable = function ( $container, backwards ) {
var $focusable = $( [] ),
// $focusableCandidates is a superset of things that
// could get matched by isFocusableElement
$focusableCandidates = $container
.find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
if ( backwards ) {
$focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
}
$focusableCandidates.each( function () {
var $this = $( this );
if ( OO.ui.isFocusableElement( $this ) ) {
$focusable = $this;
return false;
}
} );
return $focusable;
};
/**
* Get the user's language and any fallback languages.
*
* These language codes are used to localize user interface elements in the user's language.
*
* In environments that provide a localization system, this function should be overridden to
* return the user's language(s). The default implementation returns English (en) only.
*
* @return {string[]} Language codes, in descending order of priority
*/
OO.ui.getUserLanguages = function () {
return [ 'en' ];
};
/**
* Get a value in an object keyed by language code.
*
* @param {Object.<string,Mixed>} obj Object keyed by language code
* @param {string|null} [lang] Language code, if omitted or null defaults to any user language
* @param {string} [fallback] Fallback code, used if no matching language can be found
* @return {Mixed} Local value
*/
OO.ui.getLocalValue = function ( obj, lang, fallback ) {
var i, len, langs;
// Requested language
if ( obj[ lang ] ) {
return obj[ lang ];
}
// Known user language
langs = OO.ui.getUserLanguages();
for ( i = 0, len = langs.length; i < len; i++ ) {
lang = langs[ i ];
if ( obj[ lang ] ) {
return obj[ lang ];
}
}
// Fallback language
if ( obj[ fallback ] ) {
return obj[ fallback ];
}
// First existing language
for ( lang in obj ) {
return obj[ lang ];
}
return undefined;
};
/**
* Check if a node is contained within another node
*
* Similar to jQuery#contains except a list of containers can be supplied
* and a boolean argument allows you to include the container in the match list
*
* @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
* @param {HTMLElement} contained Node to find
* @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
* @return {boolean} The node is in the list of target nodes
*/
OO.ui.contains = function ( containers, contained, matchContainers ) {
var i;
if ( !Array.isArray( containers ) ) {
containers = [ containers ];
}
for ( i = containers.length - 1; i >= 0; i-- ) {
if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
return true;
}
}
return false;
};
/**
* Return a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*
* Ported from: http://underscorejs.org/underscore.js
*
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {Function}
*/
OO.ui.debounce = function ( func, wait, immediate ) {
var timeout;
return function () {
var context = this,
args = arguments,
later = function () {
timeout = null;
if ( !immediate ) {
func.apply( context, args );
}
};
if ( immediate && !timeout ) {
func.apply( context, args );
}
if ( !timeout || wait ) {
clearTimeout( timeout );
timeout = setTimeout( later, wait );
}
};
};
/**
* Puts a console warning with provided message.
*
* @param {string} message
*/
OO.ui.warnDeprecation = function ( message ) {
if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) {
// eslint-disable-next-line no-console
console.warn( message );
}
};
/**
* Returns a function, that, when invoked, will only be triggered at most once
* during a given window of time. If called again during that window, it will
* wait until the window ends and then trigger itself again.
*
* As it's not knowable to the caller whether the function will actually run
* when the wrapper is called, return values from the function are entirely
* discarded.
*
* @param {Function} func
* @param {number} wait
* @return {Function}
*/
OO.ui.throttle = function ( func, wait ) {
var context, args, timeout,
previous = 0,
run = function () {
timeout = null;
previous = OO.ui.now();
func.apply( context, args );
};
return function () {
// Check how long it's been since the last time the function was
// called, and whether it's more or less than the requested throttle
// period. If it's less, run the function immediately. If it's more,
// set a timeout for the remaining time -- but don't replace an
// existing timeout, since that'd indefinitely prolong the wait.
var remaining = wait - ( OO.ui.now() - previous );
context = this;
args = arguments;
if ( remaining <= 0 ) {
// Note: unless wait was ridiculously large, this means we'll
// automatically run the first time the function was called in a
// given period. (If you provide a wait period larger than the
// current Unix timestamp, you *deserve* unexpected behavior.)
clearTimeout( timeout );
run();
} else if ( !timeout ) {
timeout = setTimeout( run, remaining );
}
};
};
/**
* A (possibly faster) way to get the current timestamp as an integer
*
* @return {number} Current timestamp
*/
OO.ui.now = Date.now || function () {
return new Date().getTime();
};
/**
* Reconstitute a JavaScript object corresponding to a widget created by
* the PHP implementation.
*
* This is an alias for `OO.ui.Element.static.infuse()`.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
*/
OO.ui.infuse = function ( idOrNode ) {
return OO.ui.Element.static.infuse( idOrNode );
};
( function () {
/**
* Message store for the default implementation of OO.ui.msg
*
* Environments that provide a localization system should not use this, but should override
* OO.ui.msg altogether.
*
* @private
*/
var messages = {
// Tool tip for a button that moves items in a list down one place
'ooui-outline-control-move-down': 'Move item down',
// Tool tip for a button that moves items in a list up one place
'ooui-outline-control-move-up': 'Move item up',
// Tool tip for a button that removes items from a list
'ooui-outline-control-remove': 'Remove item',
// Label for the toolbar group that contains a list of all other available tools
'ooui-toolbar-more': 'More',
// Label for the fake tool that expands the full list of tools in a toolbar group
'ooui-toolgroup-expand': 'More',
// Label for the fake tool that collapses the full list of tools in a toolbar group
'ooui-toolgroup-collapse': 'Fewer',
// Default label for the accept button of a confirmation dialog
'ooui-dialog-message-accept': 'OK',
// Default label for the reject button of a confirmation dialog
'ooui-dialog-message-reject': 'Cancel',
// Title for process dialog error description
'ooui-dialog-process-error': 'Something went wrong',
// Label for process dialog dismiss error button, visible when describing errors
'ooui-dialog-process-dismiss': 'Dismiss',
// Label for process dialog retry action button, visible when describing only recoverable errors
'ooui-dialog-process-retry': 'Try again',
// Label for process dialog retry action button, visible when describing only warnings
'ooui-dialog-process-continue': 'Continue',
// Label for the file selection widget's select file button
'ooui-selectfile-button-select': 'Select a file',
// Label for the file selection widget if file selection is not supported
'ooui-selectfile-not-supported': 'File selection is not supported',
// Label for the file selection widget when no file is currently selected
'ooui-selectfile-placeholder': 'No file is selected',
// Label for the file selection widget's drop target
'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
};
/**
* Get a localized message.
*
* After the message key, message parameters may optionally be passed. In the default implementation,
* any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
* Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
* they support unnamed, ordered message parameters.
*
* In environments that provide a localization system, this function should be overridden to
* return the message translated in the user's language. The default implementation always returns
* English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
* follows.
*
* @example
* var i, iLen, button,
* messagePath = 'oojs-ui/dist/i18n/',
* languages = [ $.i18n().locale, 'ur', 'en' ],
* languageMap = {};
*
* for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
* languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
* }
*
* $.i18n().load( languageMap ).done( function() {
* // Replace the built-in `msg` only once we've loaded the internationalization.
* // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
* // you put off creating any widgets until this promise is complete, no English
* // will be displayed.
* OO.ui.msg = $.i18n;
*
* // A button displaying "OK" in the default locale
* button = new OO.ui.ButtonWidget( {
* label: OO.ui.msg( 'ooui-dialog-message-accept' ),
* icon: 'check'
* } );
* $( 'body' ).append( button.$element );
*
* // A button displaying "OK" in Urdu
* $.i18n().locale = 'ur';
* button = new OO.ui.ButtonWidget( {
* label: OO.ui.msg( 'ooui-dialog-message-accept' ),
* icon: 'check'
* } );
* $( 'body' ).append( button.$element );
* } );
*
* @param {string} key Message key
* @param {...Mixed} [params] Message parameters
* @return {string} Translated message with parameters substituted
*/
OO.ui.msg = function ( key ) {
var message = messages[ key ],
params = Array.prototype.slice.call( arguments, 1 );
if ( typeof message === 'string' ) {
// Perform $1 substitution
message = message.replace( /\$(\d+)/g, function ( unused, n ) {
var i = parseInt( n, 10 );
return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
} );
} else {
// Return placeholder if message not found
message = '[' + key + ']';
}
return message;
};
}() );
/**
* Package a message and arguments for deferred resolution.
*
* Use this when you are statically specifying a message and the message may not yet be present.
*
* @param {string} key Message key
* @param {...Mixed} [params] Message parameters
* @return {Function} Function that returns the resolved message when executed
*/
OO.ui.deferMsg = function () {
var args = arguments;
return function () {
return OO.ui.msg.apply( OO.ui, args );
};
};
/**
* Resolve a message.
*
* If the message is a function it will be executed, otherwise it will pass through directly.
*
* @param {Function|string} msg Deferred message, or message text
* @return {string} Resolved message
*/
OO.ui.resolveMsg = function ( msg ) {
if ( $.isFunction( msg ) ) {
return msg();
}
return msg;
};
/**
* @param {string} url
* @return {boolean}
*/
OO.ui.isSafeUrl = function ( url ) {
// Keep this function in sync with php/Tag.php
var i, protocolWhitelist;
function stringStartsWith( haystack, needle ) {
return haystack.substr( 0, needle.length ) === needle;
}
protocolWhitelist = [
'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
];
if ( url === '' ) {
return true;
}
for ( i = 0; i < protocolWhitelist.length; i++ ) {
if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
return true;
}
}
// This matches '//' too
if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
return true;
}
if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
return true;
}
return false;
};
/**
* Check if the user has a 'mobile' device.
*
* For our purposes this means the user is primarily using an
* on-screen keyboard, touch input instead of a mouse and may
* have a physically small display.
*
* It is left up to implementors to decide how to compute this
* so the default implementation always returns false.
*
* @return {boolean} Use is on a mobile device
*/
OO.ui.isMobile = function () {
return false;
};
/*!
* Mixin namespace.
*/
/**
* Namespace for OOjs UI mixins.
*
* Mixins are named according to the type of object they are intended to
* be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
* mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
* is intended to be mixed in to an instance of OO.ui.Widget.
*
* @class
* @singleton
*/
OO.ui.mixin = {};
/**
* Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
* that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
* connected to them and can't be interacted with.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
* to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
* @cfg {string} [id] The HTML id attribute used in the rendered tag.
* @cfg {string} [text] Text to insert
* @cfg {Array} [content] An array of content elements to append (after #text).
* Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
* Instances of OO.ui.Element will have their $element appended.
* @cfg {jQuery} [$content] Content elements to append (after #text).
* @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
* @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
* Data can also be specified with the #setData method.
*/
OO.ui.Element = function OoUiElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$ = $;
this.visible = true;
this.data = config.data;
this.$element = config.$element ||
$( document.createElement( this.getTagName() ) );
this.elementGroup = null;
// Initialization
if ( Array.isArray( config.classes ) ) {
this.$element.addClass( config.classes.join( ' ' ) );
}
if ( config.id ) {
this.$element.attr( 'id', config.id );
}
if ( config.text ) {
this.$element.text( config.text );
}
if ( config.content ) {
// The `content` property treats plain strings as text; use an
// HtmlSnippet to append HTML content. `OO.ui.Element`s get their
// appropriate $element appended.
this.$element.append( config.content.map( function ( v ) {
if ( typeof v === 'string' ) {
// Escape string so it is properly represented in HTML.
return document.createTextNode( v );
} else if ( v instanceof OO.ui.HtmlSnippet ) {
// Bypass escaping.
return v.toString();
} else if ( v instanceof OO.ui.Element ) {
return v.$element;
}
return v;
} ) );
}
if ( config.$content ) {
// The `$content` property treats plain strings as HTML.
this.$element.append( config.$content );
}
};
/* Setup */
OO.initClass( OO.ui.Element );
/* Static Properties */
/**
* The name of the HTML tag used by the element.
*
* The static value may be ignored if the #getTagName method is overridden.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Element.static.tagName = 'div';
/* Static Methods */
/**
* Reconstitute a JavaScript object corresponding to a widget created
* by the PHP implementation.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
* For `Tag` objects emitted on the HTML side (used occasionally for content)
* the value returned is a newly-created Element wrapping around the existing
* DOM node.
*/
OO.ui.Element.static.infuse = function ( idOrNode ) {
var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
// Verify that the type matches up.
// FIXME: uncomment after T89721 is fixed (see T90929)
/*
if ( !( obj instanceof this['class'] ) ) {
throw new Error( 'Infusion type mismatch!' );
}
*/
return obj;
};
/**
* Implementation helper for `infuse`; skips the type check and has an
* extra property so that only the top-level invocation touches the DOM.
*
* @private
* @param {string|HTMLElement|jQuery} idOrNode
* @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
* when the top-level widget of this infusion is inserted into DOM,
* replacing the original node; or false for top-level invocation.
* @return {OO.ui.Element}
*/
OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
// look for a cached result of a previous infusion.
var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren;
if ( typeof idOrNode === 'string' ) {
id = idOrNode;
$elem = $( document.getElementById( id ) );
} else {
$elem = $( idOrNode );
id = $elem.attr( 'id' );
}
if ( !$elem.length ) {
throw new Error( 'Widget not found: ' + id );
}
if ( $elem[ 0 ].oouiInfused ) {
$elem = $elem[ 0 ].oouiInfused;
}
data = $elem.data( 'ooui-infused' );
if ( data ) {
// cached!
if ( data === true ) {
throw new Error( 'Circular dependency! ' + id );
}
if ( domPromise ) {
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = data.constructor.static.gatherPreInfuseState( $elem, data );
// restore dynamic state after the new element is re-inserted into DOM under infused parent
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
infusedChildren = $elem.data( 'ooui-infused-children' );
if ( infusedChildren && infusedChildren.length ) {
infusedChildren.forEach( function ( data ) {
var state = data.constructor.static.gatherPreInfuseState( $elem, data );
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
} );
}
}
return data;
}
data = $elem.attr( 'data-ooui' );
if ( !data ) {
throw new Error( 'No infusion data found: ' + id );
}
try {
data = $.parseJSON( data );
} catch ( _ ) {
data = null;
}
if ( !( data && data._ ) ) {
throw new Error( 'No valid infusion data found: ' + id );
}
if ( data._ === 'Tag' ) {
// Special case: this is a raw Tag; wrap existing node, don't rebuild.
return new OO.ui.Element( { $element: $elem } );
}
parts = data._.split( '.' );
cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
if ( cls === undefined ) {
// The PHP output might be old and not including the "OO.ui" prefix
// TODO: Remove this back-compat after next major release
cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
if ( cls === undefined ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
}
// Verify that we're creating an OO.ui.Element instance
parent = cls.parent;
while ( parent !== undefined ) {
if ( parent === OO.ui.Element ) {
// Safe
break;
}
parent = parent.parent;
}
if ( parent !== OO.ui.Element ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
if ( domPromise === false ) {
top = $.Deferred();
domPromise = top.promise();
}
$elem.data( 'ooui-infused', true ); // prevent loops
data.id = id; // implicit
infusedChildren = [];
data = OO.copy( data, null, function deserialize( value ) {
var infused;
if ( OO.isPlainObject( value ) ) {
if ( value.tag ) {
infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
infusedChildren.push( infused );
// Flatten the structure
infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
infused.$element.removeData( 'ooui-infused-children' );
return infused;
}
if ( value.html !== undefined ) {
return new OO.ui.HtmlSnippet( value.html );
}
}
} );
// allow widgets to reuse parts of the DOM
data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
// rebuild widget
// eslint-disable-next-line new-cap
obj = new cls( data );
// now replace old DOM with this new DOM.
if ( top ) {
// An efficient constructor might be able to reuse the entire DOM tree of the original element,
// so only mutate the DOM if we need to.
if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
$elem.replaceWith( obj.$element );
// This element is now gone from the DOM, but if anyone is holding a reference to it,
// let's allow them to OO.ui.infuse() it and do what they expect (T105828).
// Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
$elem[ 0 ].oouiInfused = obj.$element;
}
top.resolve();
}
obj.$element.data( 'ooui-infused', obj );
obj.$element.data( 'ooui-infused-children', infusedChildren );
// set the 'data-ooui' attribute so we can identify infused widgets
obj.$element.attr( 'data-ooui', '' );
// restore dynamic state after the new element is inserted into DOM
domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
return obj;
};
/**
* Pick out parts of `node`'s DOM to be reused when infusing a widget.
*
* This method **must not** make any changes to the DOM, only find interesting pieces and add them
* to `config` (which should then be returned). Actual DOM juggling should then be done by the
* constructor, which will be given the enhanced config.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
return config;
};
/**
* Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
* (and its children) that represent an Element of the same class and the given configuration,
* generated by the PHP implementation.
*
* This method is called just before `node` is detached from the DOM. The return value of this
* function will be passed to #restorePreInfuseState after the newly created widget's #$element
* is inserted into DOM to replace `node`.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.gatherPreInfuseState = function () {
return {};
};
/**
* Get a jQuery function within a specific document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
* @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
* not in an iframe
* @return {Function} Bound jQuery function
*/
OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
function wrapper( selector ) {
return $( selector, wrapper.context );
}
wrapper.context = this.getDocument( context );
if ( $iframe ) {
wrapper.$iframe = $iframe;
}
return wrapper;
};
/**
* Get the document of an element.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
* @return {HTMLDocument|null} Document object
*/
OO.ui.Element.static.getDocument = function ( obj ) {
// jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
// Empty jQuery selections might have a context
obj.context ||
// HTMLElement
obj.ownerDocument ||
// Window
obj.document ||
// HTMLDocument
( obj.nodeType === 9 && obj ) ||
null;
};
/**
* Get the window of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
* @return {Window} Window object
*/
OO.ui.Element.static.getWindow = function ( obj ) {
var doc = this.getDocument( obj );
return doc.defaultView;
};
/**
* Get the direction of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
* @return {string} Text direction, either 'ltr' or 'rtl'
*/
OO.ui.Element.static.getDir = function ( obj ) {
var isDoc, isWin;
if ( obj instanceof jQuery ) {
obj = obj[ 0 ];
}
isDoc = obj.nodeType === 9;
isWin = obj.document !== undefined;
if ( isDoc || isWin ) {
if ( isWin ) {
obj = obj.document;
}
obj = obj.body;
}
return $( obj ).css( 'direction' );
};
/**
* Get the offset between two frames.
*
* TODO: Make this function not use recursion.
*
* @static
* @param {Window} from Window of the child frame
* @param {Window} [to=window] Window of the parent frame
* @param {Object} [offset] Offset to start with, used internally
* @return {Object} Offset object, containing left and top properties
*/
OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
var i, len, frames, frame, rect;
if ( !to ) {
to = window;
}
if ( !offset ) {
offset = { top: 0, left: 0 };
}
if ( from.parent === from ) {
return offset;
}
// Get iframe element
frames = from.parent.document.getElementsByTagName( 'iframe' );
for ( i = 0, len = frames.length; i < len; i++ ) {
if ( frames[ i ].contentWindow === from ) {
frame = frames[ i ];
break;
}
}
// Recursively accumulate offset values
if ( frame ) {
rect = frame.getBoundingClientRect();
offset.left += rect.left;
offset.top += rect.top;
if ( from !== to ) {
this.getFrameOffset( from.parent, offset );
}
}
return offset;
};
/**
* Get the offset between two elements.
*
* The two elements may be in a different frame, but in that case the frame $element is in must
* be contained in the frame $anchor is in.
*
* @static
* @param {jQuery} $element Element whose position to get
* @param {jQuery} $anchor Element to get $element's position relative to
* @return {Object} Translated position coordinates, containing top and left properties
*/
OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
var iframe, iframePos,
pos = $element.offset(),
anchorPos = $anchor.offset(),
elementDocument = this.getDocument( $element ),
anchorDocument = this.getDocument( $anchor );
// If $element isn't in the same document as $anchor, traverse up
while ( elementDocument !== anchorDocument ) {
iframe = elementDocument.defaultView.frameElement;
if ( !iframe ) {
throw new Error( '$element frame is not contained in $anchor frame' );
}
iframePos = $( iframe ).offset();
pos.left += iframePos.left;
pos.top += iframePos.top;
elementDocument = iframe.ownerDocument;
}
pos.left -= anchorPos.left;
pos.top -= anchorPos.top;
return pos;
};
/**
* Get element border sizes.
*
* @static
* @param {HTMLElement} el Element to measure
* @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
*/
OO.ui.Element.static.getBorders = function ( el ) {
var doc = el.ownerDocument,
win = doc.defaultView,
style = win.getComputedStyle( el, null ),
$el = $( el ),
top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
};
/**
* Get dimensions of an element or window.
*
* @static
* @param {HTMLElement|Window} el Element to measure
* @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
*/
OO.ui.Element.static.getDimensions = function ( el ) {
var $el, $win,
doc = el.ownerDocument || el.document,
win = doc.defaultView;
if ( win === el || el === doc.documentElement ) {
$win = $( win );
return {
borders: { top: 0, left: 0, bottom: 0, right: 0 },
scroll: {
top: $win.scrollTop(),
left: $win.scrollLeft()
},
scrollbar: { right: 0, bottom: 0 },
rect: {
top: 0,
left: 0,
bottom: $win.innerHeight(),
right: $win.innerWidth()
}
};
} else {
$el = $( el );
return {
borders: this.getBorders( el ),
scroll: {
top: $el.scrollTop(),
left: $el.scrollLeft()
},
scrollbar: {
right: $el.innerWidth() - el.clientWidth,
bottom: $el.innerHeight() - el.clientHeight
},
rect: el.getBoundingClientRect()
};
}
};
/**
* Get scrollable object parent
*
* documentElement can't be used to get or set the scrollTop
* property on Blink. Changing and testing its value lets us
* use 'body' or 'documentElement' based on what is working.
*
* https://code.google.com/p/chromium/issues/detail?id=303131
*
* @static
* @param {HTMLElement} el Element to find scrollable parent for
* @return {HTMLElement} Scrollable parent
*/
OO.ui.Element.static.getRootScrollableElement = function ( el ) {
var scrollTop, body;
if ( OO.ui.scrollableElement === undefined ) {
body = el.ownerDocument.body;
scrollTop = body.scrollTop;
body.scrollTop = 1;
if ( body.scrollTop === 1 ) {
body.scrollTop = scrollTop;
OO.ui.scrollableElement = 'body';
} else {
OO.ui.scrollableElement = 'documentElement';
}
}
return el.ownerDocument[ OO.ui.scrollableElement ];
};
/**
* Get closest scrollable container.
*
* Traverses up until either a scrollable element or the root is reached, in which case the window
* will be returned.
*
* @static
* @param {HTMLElement} el Element to find scrollable container for
* @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
var i, val,
// props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
props = [ 'overflow-x', 'overflow-y' ],
$parent = $( el ).parent();
if ( dimension === 'x' || dimension === 'y' ) {
props = [ 'overflow-' + dimension ];
}
while ( $parent.length ) {
if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
return $parent[ 0 ];
}
i = props.length;
while ( i-- ) {
val = $parent.css( props[ i ] );
if ( val === 'auto' || val === 'scroll' ) {
return $parent[ 0 ];
}
}
$parent = $parent.parent();
}
return this.getDocument( el ).body;
};
/**
* Scroll element into view.
*
* @static
* @param {HTMLElement} el Element to scroll into view
* @param {Object} [config] Configuration options
* @param {string} [config.duration='fast'] jQuery animation duration value
* @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
* to scroll in both directions
* @param {Function} [config.complete] Function to call when scrolling completes.
* Deprecated since 0.15.4, use the return promise instead.
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.static.scrollIntoView = function ( el, config ) {
var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window,
deferred = $.Deferred();
// Configuration initialization
config = config || {};
animations = {};
callback = typeof config.complete === 'function' && config.complete;
if ( callback ) {
OO.ui.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
}
container = this.getClosestScrollableContainer( el, config.direction );
$container = $( container );
elementDimensions = this.getDimensions( el );
containerDimensions = this.getDimensions( container );
$window = $( this.getWindow( el ) );
// Compute the element's position relative to the container
if ( $container.is( 'html, body' ) ) {
// If the scrollable container is the root, this is easy
position = {
top: elementDimensions.rect.top,
bottom: $window.innerHeight() - elementDimensions.rect.bottom,
left: elementDimensions.rect.left,
right: $window.innerWidth() - elementDimensions.rect.right
};
} else {
// Otherwise, we have to subtract el's coordinates from container's coordinates
position = {
top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
};
}
if ( !config.direction || config.direction === 'y' ) {
if ( position.top < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + position.top;
} else if ( position.top > 0 && position.bottom < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
}
}
if ( !config.direction || config.direction === 'x' ) {
if ( position.left < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + position.left;
} else if ( position.left > 0 && position.right < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
}
}
if ( !$.isEmptyObject( animations ) ) {
$container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
$container.queue( function ( next ) {
if ( callback ) {
callback();
}
deferred.resolve();
next();
} );
} else {
if ( callback ) {
callback();
}
deferred.resolve();
}
return deferred.promise();
};
/**
* Force the browser to reconsider whether it really needs to render scrollbars inside the element
* and reserve space for them, because it probably doesn't.
*
* Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
* similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
* to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
* and then reattach (or show) them back.
*
* @static
* @param {HTMLElement} el Element to reconsider the scrollbars on
*/
OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
var i, len, scrollLeft, scrollTop, nodes = [];
// Save scroll position
scrollLeft = el.scrollLeft;
scrollTop = el.scrollTop;
// Detach all children
while ( el.firstChild ) {
nodes.push( el.firstChild );
el.removeChild( el.firstChild );
}
// Force reflow
void el.offsetHeight;
// Reattach all children
for ( i = 0, len = nodes.length; i < len; i++ ) {
el.appendChild( nodes[ i ] );
}
// Restore scroll position (no-op if scrollbars disappeared)
el.scrollLeft = scrollLeft;
el.scrollTop = scrollTop;
};
/* Methods */
/**
* Toggle visibility of an element.
*
* @param {boolean} [show] Make element visible, omit to toggle visibility
* @fires visible
* @chainable
*/
OO.ui.Element.prototype.toggle = function ( show ) {
show = show === undefined ? !this.visible : !!show;
if ( show !== this.isVisible() ) {
this.visible = show;
this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
this.emit( 'toggle', show );
}
return this;
};
/**
* Check if element is visible.
*
* @return {boolean} element is visible
*/
OO.ui.Element.prototype.isVisible = function () {
return this.visible;
};
/**
* Get element data.
*
* @return {Mixed} Element data
*/
OO.ui.Element.prototype.getData = function () {
return this.data;
};
/**
* Set element data.
*
* @param {Mixed} data Element data
* @chainable
*/
OO.ui.Element.prototype.setData = function ( data ) {
this.data = data;
return this;
};
/**
* Check if element supports one or more methods.
*
* @param {string|string[]} methods Method or list of methods to check
* @return {boolean} All methods are supported
*/
OO.ui.Element.prototype.supports = function ( methods ) {
var i, len,
support = 0;
methods = Array.isArray( methods ) ? methods : [ methods ];
for ( i = 0, len = methods.length; i < len; i++ ) {
if ( $.isFunction( this[ methods[ i ] ] ) ) {
support++;
}
}
return methods.length === support;
};
/**
* Update the theme-provided classes.
*
* @localdoc This is called in element mixins and widget classes any time state changes.
* Updating is debounced, minimizing overhead of changing multiple attributes and
* guaranteeing that theme updates do not occur within an element's constructor
*/
OO.ui.Element.prototype.updateThemeClasses = function () {
OO.ui.theme.queueUpdateElementClasses( this );
};
/**
* Get the HTML tag name.
*
* Override this method to base the result on instance information.
*
* @return {string} HTML tag name
*/
OO.ui.Element.prototype.getTagName = function () {
return this.constructor.static.tagName;
};
/**
* Check if the element is attached to the DOM
*
* @return {boolean} The element is attached to the DOM
*/
OO.ui.Element.prototype.isElementAttached = function () {
return $.contains( this.getElementDocument(), this.$element[ 0 ] );
};
/**
* Get the DOM document.
*
* @return {HTMLDocument} Document object
*/
OO.ui.Element.prototype.getElementDocument = function () {
// Don't cache this in other ways either because subclasses could can change this.$element
return OO.ui.Element.static.getDocument( this.$element );
};
/**
* Get the DOM window.
*
* @return {Window} Window object
*/
OO.ui.Element.prototype.getElementWindow = function () {
return OO.ui.Element.static.getWindow( this.$element );
};
/**
* Get closest scrollable container.
*
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
};
/**
* Get group element is in.
*
* @return {OO.ui.mixin.GroupElement|null} Group element, null if none
*/
OO.ui.Element.prototype.getElementGroup = function () {
return this.elementGroup;
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
*/
OO.ui.Element.prototype.setElementGroup = function ( group ) {
this.elementGroup = group;
return this;
};
/**
* Scroll element into view.
*
* @param {Object} [config] Configuration options
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
if (
!this.isElementAttached() ||
!this.isVisible() ||
( this.getElementGroup() && !this.getElementGroup().isVisible() )
) {
return $.Deferred().resolve();
}
return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
};
/**
* Restore the pre-infusion dynamic state for this widget.
*
* This method is called after #$element has been inserted into DOM. The parameter is the return
* value of #gatherPreInfuseState.
*
* @protected
* @param {Object} state
*/
OO.ui.Element.prototype.restorePreInfuseState = function () {
};
/**
* Wraps an HTML snippet for use with configuration values which default
* to strings. This bypasses the default html-escaping done to string
* values.
*
* @class
*
* @constructor
* @param {string} [content] HTML content
*/
OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
// Properties
this.content = content;
};
/* Setup */
OO.initClass( OO.ui.HtmlSnippet );
/* Methods */
/**
* Render into HTML.
*
* @return {string} Unchanged HTML snippet.
*/
OO.ui.HtmlSnippet.prototype.toString = function () {
return this.content;
};
/**
* Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
* that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
* See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
* {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
* {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Layout = function OoUiLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Layout.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Initialization
this.$element.addClass( 'oo-ui-layout' );
};
/* Setup */
OO.inheritClass( OO.ui.Layout, OO.ui.Element );
OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
/**
* Widgets are compositions of one or more OOjs UI elements that users can both view
* and interact with. All widgets can be configured and modified via a standard API,
* and their state can change dynamically according to a model.
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
* appearance reflects this state.
*/
OO.ui.Widget = function OoUiWidget( config ) {
// Initialize config
config = $.extend( { disabled: false }, config );
// Parent constructor
OO.ui.Widget.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.disabled = null;
this.wasDisabled = null;
// Initialization
this.$element.addClass( 'oo-ui-widget' );
this.setDisabled( !!config.disabled );
};
/* Setup */
OO.inheritClass( OO.ui.Widget, OO.ui.Element );
OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
/* Static Properties */
/**
* Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
* wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
* handling.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.Widget.static.supportsSimpleLabel = false;
/* Events */
/**
* @event disable
*
* A 'disable' event is emitted when the disabled state of the widget changes
* (i.e. on disable **and** enable).
*
* @param {boolean} disabled Widget is disabled
*/
/**
* @event toggle
*
* A 'toggle' event is emitted when the visibility of the widget changes.
*
* @param {boolean} visible Widget is visible
*/
/* Methods */
/**
* Check if the widget is disabled.
*
* @return {boolean} Widget is disabled
*/
OO.ui.Widget.prototype.isDisabled = function () {
return this.disabled;
};
/**
* Set the 'disabled' state of the widget.
*
* When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
*
* @param {boolean} disabled Disable widget
* @chainable
*/
OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
var isDisabled;
this.disabled = !!disabled;
isDisabled = this.isDisabled();
if ( isDisabled !== this.wasDisabled ) {
this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
this.$element.attr( 'aria-disabled', isDisabled.toString() );
this.emit( 'disable', isDisabled );
this.updateThemeClasses();
}
this.wasDisabled = isDisabled;
return this;
};
/**
* Update the disabled state, in case of changes in parent widget.
*
* @chainable
*/
OO.ui.Widget.prototype.updateDisabled = function () {
this.setDisabled( this.disabled );
return this;
};
/**
* Theme logic.
*
* @abstract
* @class
*
* @constructor
*/
OO.ui.Theme = function OoUiTheme() {
this.elementClassesQueue = [];
this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
};
/* Setup */
OO.initClass( OO.ui.Theme );
/* Methods */
/**
* Get a list of classes to be applied to a widget.
*
* The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
* otherwise state transitions will not work properly.
*
* @param {OO.ui.Element} element Element for which to get classes
* @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
*/
OO.ui.Theme.prototype.getElementClasses = function () {
return { on: [], off: [] };
};
/**
* Update CSS classes provided by the theme.
*
* For elements with theme logic hooks, this should be called any time there's a state change.
*
* @param {OO.ui.Element} element Element for which to update classes
*/
OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
var $elements = $( [] ),
classes = this.getElementClasses( element );
if ( element.$icon ) {
$elements = $elements.add( element.$icon );
}
if ( element.$indicator ) {
$elements = $elements.add( element.$indicator );
}
$elements
.removeClass( classes.off.join( ' ' ) )
.addClass( classes.on.join( ' ' ) );
};
/**
* @private
*/
OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
var i;
for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
this.updateElementClasses( this.elementClassesQueue[ i ] );
}
// Clear the queue
this.elementClassesQueue = [];
};
/**
* Queue #updateElementClasses to be called for this element.
*
* @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
* to make them synchronous.
*
* @param {OO.ui.Element} element Element for which to update classes
*/
OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
// Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
// the most common case (this method is often called repeatedly for the same element).
if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
return;
}
this.elementClassesQueue.push( element );
this.debouncedUpdateQueuedElementClasses();
};
/**
* Get the transition duration in milliseconds for dialogs opening/closing
*
* The dialog should be fully rendered this many milliseconds after the
* ready process has executed.
*
* @return {number} Transition duration in milliseconds
*/
OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
return 0;
};
/**
* The TabIndexedElement class is an attribute mixin used to add additional functionality to an
* element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
* order in which users will navigate through the focusable elements via the "tab" key.
*
* @example
* // TabIndexedElement is mixed into the ButtonWidget class
* // to provide a tabIndex property.
* var button1 = new OO.ui.ButtonWidget( {
* label: 'fourth',
* tabIndex: 4
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'second',
* tabIndex: 2
* } );
* var button3 = new OO.ui.ButtonWidget( {
* label: 'third',
* tabIndex: 3
* } );
* var button4 = new OO.ui.ButtonWidget( {
* label: 'first',
* tabIndex: 1
* } );
* $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
* the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
* functionality will be applied to it instead.
* @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
* order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
* to remove the element from the tab-navigation flow.
*/
OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
// Configuration initialization
config = $.extend( { tabIndex: 0 }, config );
// Properties
this.$tabIndexed = null;
this.tabIndex = null;
// Events
this.connect( this, { disable: 'onTabIndexedElementDisable' } );
// Initialization
this.setTabIndex( config.tabIndex );
this.setTabIndexedElement( config.$tabIndexed || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Set the element that should use the tabindex functionality.
*
* This method is used to retarget a tabindex mixin so that its functionality applies
* to the specified element. If an element is currently using the functionality, the mixin’s
* effect on that element is removed before the new element is set up.
*
* @param {jQuery} $tabIndexed Element that should use the tabindex functionality
* @chainable
*/
OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
var tabIndex = this.tabIndex;
// Remove attributes from old $tabIndexed
this.setTabIndex( null );
// Force update of new $tabIndexed
this.$tabIndexed = $tabIndexed;
this.tabIndex = tabIndex;
return this.updateTabIndex();
};
/**
* Set the value of the tabindex.
*
* @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
* @chainable
*/
OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
if ( this.tabIndex !== tabIndex ) {
this.tabIndex = tabIndex;
this.updateTabIndex();
}
return this;
};
/**
* Update the `tabindex` attribute, in case of changes to tab index or
* disabled state.
*
* @private
* @chainable
*/
OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
if ( this.$tabIndexed ) {
if ( this.tabIndex !== null ) {
// Do not index over disabled elements
this.$tabIndexed.attr( {
tabindex: this.isDisabled() ? -1 : this.tabIndex,
// Support: ChromeVox and NVDA
// These do not seem to inherit aria-disabled from parent elements
'aria-disabled': this.isDisabled().toString()
} );
} else {
this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
}
}
return this;
};
/**
* Handle disable events.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
this.updateTabIndex();
};
/**
* Get the value of the tabindex.
*
* @return {number|null} Tabindex value
*/
OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
return this.tabIndex;
};
/**
* ButtonElement is often mixed into other classes to generate a button, which is a clickable
* interface element that can be configured with access keys for accessibility.
* See the [OOjs UI documentation on MediaWiki] [1] for examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$button] The button element created by the class.
* If this configuration is omitted, the button element will use a generated `<a>`.
* @cfg {boolean} [framed=true] Render the button with a frame
*/
OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$button = null;
this.framed = null;
this.active = config.active !== undefined && config.active;
this.onMouseUpHandler = this.onMouseUp.bind( this );
this.onMouseDownHandler = this.onMouseDown.bind( this );
this.onKeyDownHandler = this.onKeyDown.bind( this );
this.onKeyUpHandler = this.onKeyUp.bind( this );
this.onClickHandler = this.onClick.bind( this );
this.onKeyPressHandler = this.onKeyPress.bind( this );
// Initialization
this.$element.addClass( 'oo-ui-buttonElement' );
this.toggleFramed( config.framed === undefined || config.framed );
this.setButtonElement( config.$button || $( '<a>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.ButtonElement );
/* Static Properties */
/**
* Cancel mouse down events.
*
* This property is usually set to `true` to prevent the focus from changing when the button is clicked.
* Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
* use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
* parent widget.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
/* Events */
/**
* A 'click' event is emitted when the button element is clicked.
*
* @event click
*/
/* Methods */
/**
* Set the button element.
*
* This method is used to retarget a button mixin so that its functionality applies to
* the specified button element instead of the one created by the class. If a button element
* is already set, the method will remove the mixin’s effect on that element.
*
* @param {jQuery} $button Element to use as button
*/
OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
if ( this.$button ) {
this.$button
.removeClass( 'oo-ui-buttonElement-button' )
.removeAttr( 'role accesskey' )
.off( {
mousedown: this.onMouseDownHandler,
keydown: this.onKeyDownHandler,
click: this.onClickHandler,
keypress: this.onKeyPressHandler
} );
}
this.$button = $button
.addClass( 'oo-ui-buttonElement-button' )
.on( {
mousedown: this.onMouseDownHandler,
keydown: this.onKeyDownHandler,
click: this.onClickHandler,
keypress: this.onKeyPressHandler
} );
// Add `role="button"` on `<a>` elements, where it's needed
// `toUppercase()` is added for XHTML documents
if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
this.$button.attr( 'role', 'button' );
}
};
/**
* Handles mouse down events.
*
* @protected
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
return;
}
this.$element.addClass( 'oo-ui-buttonElement-pressed' );
// Run the mouseup handler no matter where the mouse is when the button is let go, so we can
// reliably remove the pressed class
this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
// Prevent change of focus unless specifically configured otherwise
if ( this.constructor.static.cancelButtonMouseDownEvents ) {
return false;
}
};
/**
* Handles mouse up events.
*
* @protected
* @param {MouseEvent} e Mouse up event
*/
OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
return;
}
this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
// Stop listening for mouseup, since we only needed this once
this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
};
/**
* Handles mouse click events.
*
* @protected
* @param {jQuery.Event} e Mouse click event
* @fires click
*/
OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
if ( this.emit( 'click' ) ) {
return false;
}
}
};
/**
* Handles key down events.
*
* @protected
* @param {jQuery.Event} e Key down event
*/
OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
return;
}
this.$element.addClass( 'oo-ui-buttonElement-pressed' );
// Run the keyup handler no matter where the key is when the button is let go, so we can
// reliably remove the pressed class
this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
};
/**
* Handles key up events.
*
* @protected
* @param {KeyboardEvent} e Key up event
*/
OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
return;
}
this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
// Stop listening for keyup, since we only needed this once
this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
};
/**
* Handles key press events.
*
* @protected
* @param {jQuery.Event} e Key press event
* @fires click
*/
OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
if ( this.emit( 'click' ) ) {
return false;
}
}
};
/**
* Check if button has a frame.
*
* @return {boolean} Button is framed
*/
OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
return this.framed;
};
/**
* Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
*
* @param {boolean} [framed] Make button framed, omit to toggle
* @chainable
*/
OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
framed = framed === undefined ? !this.framed : !!framed;
if ( framed !== this.framed ) {
this.framed = framed;
this.$element
.toggleClass( 'oo-ui-buttonElement-frameless', !framed )
.toggleClass( 'oo-ui-buttonElement-framed', framed );
this.updateThemeClasses();
}
return this;
};
/**
* Set the button's active state.
*
* The active state can be set on:
*
* - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
* - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
* - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
*
* @protected
* @param {boolean} value Make button active
* @chainable
*/
OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
this.active = !!value;
this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
this.updateThemeClasses();
return this;
};
/**
* Check if the button is active
*
* @protected
* @return {boolean} The button is active
*/
OO.ui.mixin.ButtonElement.prototype.isActive = function () {
return this.active;
};
/**
* Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
* {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
* items from the group is done through the interface the class provides.
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$group] The container element created by the class. If this configuration
* is omitted, the group element will use a generated `<div>`.
*/
OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$group = null;
this.items = [];
this.aggregateItemEvents = {};
// Initialization
this.setGroupElement( config.$group || $( '<div>' ) );
};
/* Events */
/**
* @event change
*
* A change event is emitted when the set of selected items changes.
*
* @param {OO.ui.Element[]} items Items currently in the group
*/
/* Methods */
/**
* Set the group element.
*
* If an element is already set, items will be moved to the new element.
*
* @param {jQuery} $group Element to use as group
*/
OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
var i, len;
this.$group = $group;
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.$group.append( this.items[ i ].$element );
}
};
/**
* Check if a group contains no items.
*
* @return {boolean} Group is empty
*/
OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
return !this.items.length;
};
/**
* Get all items in the group.
*
* The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
* when synchronizing groups of items, or whenever the references are required (e.g., when removing items
* from a group).
*
* @return {OO.ui.Element[]} An array of items.
*/
OO.ui.mixin.GroupElement.prototype.getItems = function () {
return this.items.slice( 0 );
};
/**
* Get an item by its data.
*
* Only the first item with matching data will be returned. To return all matching items,
* use the #getItemsFromData method.
*
* @param {Object} data Item data to search for
* @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
*/
OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
var i, len, item,
hash = OO.getHash( data );
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( hash === OO.getHash( item.getData() ) ) {
return item;
}
}
return null;
};
/**
* Get items by their data.
*
* All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
*
* @param {Object} data Item data to search for
* @return {OO.ui.Element[]} Items with equivalent data
*/
OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
var i, len, item,
hash = OO.getHash( data ),
items = [];
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( hash === OO.getHash( item.getData() ) ) {
items.push( item );
}
}
return items;
};
/**
* Aggregate the events emitted by the group.
*
* When events are aggregated, the group will listen to all contained items for the event,
* and then emit the event under a new name. The new event will contain an additional leading
* parameter containing the item that emitted the original event. Other arguments emitted from
* the original event are passed through.
*
* @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
* aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
* A `null` value will remove aggregated events.
* @throws {Error} An error is thrown if aggregation already exists.
*/
OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
var i, len, item, add, remove, itemEvent, groupEvent;
for ( itemEvent in events ) {
groupEvent = events[ itemEvent ];
// Remove existing aggregated event
if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
// Don't allow duplicate aggregations
if ( groupEvent ) {
throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
}
// Remove event aggregation from existing items
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( item.connect && item.disconnect ) {
remove = {};
remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
item.disconnect( this, remove );
}
}
// Prevent future items from aggregating event
delete this.aggregateItemEvents[ itemEvent ];
}
// Add new aggregate event
if ( groupEvent ) {
// Make future items aggregate event
this.aggregateItemEvents[ itemEvent ] = groupEvent;
// Add event aggregation to existing items
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if ( item.connect && item.disconnect ) {
add = {};
add[ itemEvent ] = [ 'emit', groupEvent, item ];
item.connect( this, add );
}
}
}
}
};
/**
* Add items to the group.
*
* Items will be added to the end of the group array unless the optional `index` parameter specifies
* a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
*
* @param {OO.ui.Element[]} items An array of items to add to the group
* @param {number} [index] Index of the insertion point
* @chainable
*/
OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
var i, len, item, itemEvent, events, currentIndex,
itemElements = [];
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
// Check if item exists then remove it first, effectively "moving" it
currentIndex = this.items.indexOf( item );
if ( currentIndex >= 0 ) {
this.removeItems( [ item ] );
// Adjust index to compensate for removal
if ( currentIndex < index ) {
index--;
}
}
// Add the item
if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
events = {};
for ( itemEvent in this.aggregateItemEvents ) {
events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
}
item.connect( this, events );
}
item.setElementGroup( this );
itemElements.push( item.$element.get( 0 ) );
}
if ( index === undefined || index < 0 || index >= this.items.length ) {
this.$group.append( itemElements );
this.items.push.apply( this.items, items );
} else if ( index === 0 ) {
this.$group.prepend( itemElements );
this.items.unshift.apply( this.items, items );
} else {
this.items[ index ].$element.before( itemElements );
this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
}
this.emit( 'change', this.getItems() );
return this;
};
/**
* Remove the specified items from a group.
*
* Removed items are detached (not removed) from the DOM so that they may be reused.
* To remove all items from a group, you may wish to use the #clearItems method instead.
*
* @param {OO.ui.Element[]} items An array of items to remove
* @chainable
*/
OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
var i, len, item, index, events, itemEvent;
// Remove specific items
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
index = this.items.indexOf( item );
if ( index !== -1 ) {
if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
events = {};
for ( itemEvent in this.aggregateItemEvents ) {
events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
}
item.disconnect( this, events );
}
item.setElementGroup( null );
this.items.splice( index, 1 );
item.$element.detach();
}
}
this.emit( 'change', this.getItems() );
return this;
};
/**
* Clear all items from the group.
*
* Cleared items are detached from the DOM, not removed, so that they may be reused.
* To remove only a subset of items from a group, use the #removeItems method.
*
* @chainable
*/
OO.ui.mixin.GroupElement.prototype.clearItems = function () {
var i, len, item, remove, itemEvent;
// Remove all items
for ( i = 0, len = this.items.length; i < len; i++ ) {
item = this.items[ i ];
if (
item.connect && item.disconnect &&
!$.isEmptyObject( this.aggregateItemEvents )
) {
remove = {};
if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
}
item.disconnect( this, remove );
}
item.setElementGroup( null );
item.$element.detach();
}
this.emit( 'change', this.getItems() );
this.items = [];
return this;
};
/**
* IconElement is often mixed into other classes to generate an icon.
* Icons are graphics, about the size of normal text. They are used to aid the user
* in locating a control or to convey information in a space-efficient way. See the
* [OOjs UI documentation on MediaWiki] [1] for a list of icons
* included in the library.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
* the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
* the icon element be set to an existing icon instead of the one generated by this class, set a
* value using a jQuery selection. For example:
*
* // Use a <div> tag instead of a <span>
* $icon: $("<div>")
* // Use an existing icon element instead of the one generated by the class
* $icon: this.$element
* // Use an icon element from a child widget
* $icon: this.childwidget.$element
* @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
* symbolic names. A map is used for i18n purposes and contains a `default` icon
* name and additional names keyed by language code. The `default` name is used when no icon is keyed
* by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
* See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
* @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
* text. The icon title is displayed when users move the mouse over the icon.
*/
OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$icon = null;
this.icon = null;
this.iconTitle = null;
// Initialization
this.setIcon( config.icon || this.constructor.static.icon );
this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
this.setIconElement( config.$icon || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IconElement );
/* Static Properties */
/**
* The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
* for i18n purposes and contains a `default` icon name and additional names keyed by
* language code. The `default` name is used when no icon is keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
*
* Note: the static property will be overridden if the #icon configuration is used.
*
* @static
* @inheritable
* @property {Object|string}
*/
OO.ui.mixin.IconElement.static.icon = null;
/**
* The icon title, displayed when users move the mouse over the icon. The value can be text, a
* function that returns title text, or `null` for no title.
*
* The static property will be overridden if the #iconTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IconElement.static.iconTitle = null;
/* Methods */
/**
* Set the icon element. This method is used to retarget an icon mixin so that its functionality
* applies to the specified icon element instead of the one created by the class. If an icon
* element is already set, the mixin’s effect on that element is removed. Generated CSS classes
* and mixin methods will no longer affect the element.
*
* @param {jQuery} $icon Element to use as icon
*/
OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
if ( this.$icon ) {
this.$icon
.removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
.removeAttr( 'title' );
}
this.$icon = $icon
.addClass( 'oo-ui-iconElement-icon' )
.toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', this.iconTitle );
}
this.updateThemeClasses();
};
/**
* Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
* The icon parameter can also be set to a map of icon names. See the #icon config setting
* for an example.
*
* @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
* by language code, or `null` to remove the icon.
* @chainable
*/
OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
if ( this.icon !== icon ) {
if ( this.$icon ) {
if ( this.icon !== null ) {
this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
}
if ( icon !== null ) {
this.$icon.addClass( 'oo-ui-icon-' + icon );
}
}
this.icon = icon;
}
this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
this.updateThemeClasses();
return this;
};
/**
* Set the icon title. Use `null` to remove the title.
*
* @param {string|Function|null} iconTitle A text string used as the icon title,
* a function that returns title text, or `null` for no title.
* @chainable
*/
OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
iconTitle = typeof iconTitle === 'function' ||
( typeof iconTitle === 'string' && iconTitle.length ) ?
OO.ui.resolveMsg( iconTitle ) : null;
if ( this.iconTitle !== iconTitle ) {
this.iconTitle = iconTitle;
if ( this.$icon ) {
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', iconTitle );
} else {
this.$icon.removeAttr( 'title' );
}
}
}
return this;
};
/**
* Get the symbolic name of the icon.
*
* @return {string} Icon name
*/
OO.ui.mixin.IconElement.prototype.getIcon = function () {
return this.icon;
};
/**
* Get the icon title. The title text is displayed when a user moves the mouse over the icon.
*
* @return {string} Icon title text
*/
OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
return this.iconTitle;
};
/**
* IndicatorElement is often mixed into other classes to generate an indicator.
* Indicators are small graphics that are generally used in two ways:
*
* - To draw attention to the status of an item. For example, an indicator might be
* used to show that an item in a list has errors that need to be resolved.
* - To clarify the function of a control that acts in an exceptional way (a button
* that opens a menu instead of performing an action directly, for example).
*
* For a list of indicators included in the library, please see the
* [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$indicator] The indicator element created by the class. If this
* configuration is omitted, the indicator element will use a generated `<span>`.
* @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
* See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
* in the library.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
* @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
* or a function that returns title text. The indicator title is displayed when users move
* the mouse over the indicator.
*/
OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$indicator = null;
this.indicator = null;
this.indicatorTitle = null;
// Initialization
this.setIndicator( config.indicator || this.constructor.static.indicator );
this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
this.setIndicatorElement( config.$indicator || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IndicatorElement );
/* Static Properties */
/**
* Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
* The static property will be overridden if the #indicator configuration is used.
*
* @static
* @inheritable
* @property {string|null}
*/
OO.ui.mixin.IndicatorElement.static.indicator = null;
/**
* A text string used as the indicator title, a function that returns title text, or `null`
* for no title. The static property will be overridden if the #indicatorTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
/* Methods */
/**
* Set the indicator element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $indicator Element to use as indicator
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
if ( this.$indicator ) {
this.$indicator
.removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
.removeAttr( 'title' );
}
this.$indicator = $indicator
.addClass( 'oo-ui-indicatorElement-indicator' )
.toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
if ( this.indicatorTitle !== null ) {
this.$indicator.attr( 'title', this.indicatorTitle );
}
this.updateThemeClasses();
};
/**
* Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
*
* @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
* @chainable
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
if ( this.indicator !== indicator ) {
if ( this.$indicator ) {
if ( this.indicator !== null ) {
this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
}
if ( indicator !== null ) {
this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
}
}
this.indicator = indicator;
}
this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
this.updateThemeClasses();
return this;
};
/**
* Set the indicator title.
*
* The title is displayed when a user moves the mouse over the indicator.
*
* @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
* `null` for no indicator title
* @chainable
*/
OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
indicatorTitle = typeof indicatorTitle === 'function' ||
( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
OO.ui.resolveMsg( indicatorTitle ) : null;
if ( this.indicatorTitle !== indicatorTitle ) {
this.indicatorTitle = indicatorTitle;
if ( this.$indicator ) {
if ( this.indicatorTitle !== null ) {
this.$indicator.attr( 'title', indicatorTitle );
} else {
this.$indicator.removeAttr( 'title' );
}
}
}
return this;
};
/**
* Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
*
* @return {string} Symbolic name of indicator
*/
OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
return this.indicator;
};
/**
* Get the indicator title.
*
* The title is displayed when a user moves the mouse over the indicator.
*
* @return {string} Indicator title text
*/
OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
return this.indicatorTitle;
};
/**
* LabelElement is often mixed into other classes to generate a label, which
* helps identify the function of an interface element.
* See the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$label] The label element created by the class. If this
* configuration is omitted, the label element will use a generated `<span>`.
* @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
* as a plaintext string, a jQuery selection of elements, or a function that will produce a string
* in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
*/
OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$label = null;
this.label = null;
// Initialization
this.setLabel( config.label || this.constructor.static.label );
this.setLabelElement( config.$label || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.LabelElement );
/* Events */
/**
* @event labelChange
* @param {string} value
*/
/* Static Properties */
/**
* The label text. The label can be specified as a plaintext string, a function that will
* produce a string in the future, or `null` for no label. The static value will
* be overridden if a label is specified with the #label config option.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.LabelElement.static.label = null;
/* Static methods */
/**
* Highlight the first occurrence of the query in the given text
*
* @param {string} text Text
* @param {string} query Query to find
* @return {jQuery} Text with the first match of the query
* sub-string wrapped in highlighted span
*/
OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) {
var $result = $( '<span>' ),
offset = text.toLowerCase().indexOf( query.toLowerCase() );
if ( !query.length || offset === -1 ) {
return $result.text( text );
}
$result.append(
document.createTextNode( text.slice( 0, offset ) ),
$( '<span>' )
.addClass( 'oo-ui-labelElement-label-highlight' )
.text( text.slice( offset, offset + query.length ) ),
document.createTextNode( text.slice( offset + query.length ) )
);
return $result.contents();
};
/* Methods */
/**
* Set the label element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $label Element to use as label
*/
OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
if ( this.$label ) {
this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
}
this.$label = $label.addClass( 'oo-ui-labelElement-label' );
this.setLabelContent( this.label );
};
/**
* Set the label.
*
* An empty string will result in the label being hidden. A string containing only whitespace will
* be converted to a single ` `.
*
* @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
* text; or null for no label
* @chainable
*/
OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
if ( this.label !== label ) {
if ( this.$label ) {
this.setLabelContent( label );
}
this.label = label;
this.emit( 'labelChange' );
}
this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
return this;
};
/**
* Set the label as plain text with a highlighted query
*
* @param {string} text Text label to set
* @param {string} query Substring of text to highlight
* @chainable
*/
OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) {
return this.setLabel( this.constructor.static.highlightQuery( text, query ) );
};
/**
* Get the label.
*
* @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
* text; or null for no label
*/
OO.ui.mixin.LabelElement.prototype.getLabel = function () {
return this.label;
};
/**
* Set the content of the label.
*
* Do not call this method until after the label element has been set by #setLabelElement.
*
* @private
* @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
* text; or null for no label
*/
OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
if ( typeof label === 'string' ) {
if ( label.match( /^\s*$/ ) ) {
// Convert whitespace only string to a single non-breaking space
this.$label.html( ' ' );
} else {
this.$label.text( label );
}
} else if ( label instanceof OO.ui.HtmlSnippet ) {
this.$label.html( label.toString() );
} else if ( label instanceof jQuery ) {
this.$label.empty().append( label );
} else {
this.$label.empty();
}
};
/**
* The FlaggedElement class is an attribute mixin, meaning that it is used to add
* additional functionality to an element created by another class. The class provides
* a ‘flags’ property assigned the name (or an array of names) of styling flags,
* which are used to customize the look and feel of a widget to better describe its
* importance and functionality.
*
* The library currently contains the following styling flags for general use:
*
* - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
* - **destructive**: Destructive styling is applied to convey that the widget will remove something.
* - **constructive**: Constructive styling is applied to convey that the widget will create something.
*
* The flags affect the appearance of the buttons:
*
* @example
* // FlaggedElement is mixed into ButtonWidget to provide styling flags
* var button1 = new OO.ui.ButtonWidget( {
* label: 'Constructive',
* flags: 'constructive'
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'Destructive',
* flags: 'destructive'
* } );
* var button3 = new OO.ui.ButtonWidget( {
* label: 'Progressive',
* flags: 'progressive'
* } );
* $( 'body' ).append( button1.$element, button2.$element, button3.$element );
*
* {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
* Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
* @cfg {jQuery} [$flagged] The flagged element. By default,
* the flagged functionality is applied to the element created by the class ($element).
* If a different element is specified, the flagged functionality will be applied to it instead.
*/
OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.flags = {};
this.$flagged = null;
// Initialization
this.setFlags( config.flags );
this.setFlaggedElement( config.$flagged || this.$element );
};
/* Events */
/**
* @event flag
* A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
* parameter contains the name of each modified flag and indicates whether it was
* added or removed.
*
* @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
* that the flag was added, `false` that the flag was removed.
*/
/* Methods */
/**
* Set the flagged element.
*
* This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
* If an element is already set, the method will remove the mixin’s effect on that element.
*
* @param {jQuery} $flagged Element that should be flagged
*/
OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
var classNames = Object.keys( this.flags ).map( function ( flag ) {
return 'oo-ui-flaggedElement-' + flag;
} ).join( ' ' );
if ( this.$flagged ) {
this.$flagged.removeClass( classNames );
}
this.$flagged = $flagged.addClass( classNames );
};
/**
* Check if the specified flag is set.
*
* @param {string} flag Name of flag
* @return {boolean} The flag is set
*/
OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
// This may be called before the constructor, thus before this.flags is set
return this.flags && ( flag in this.flags );
};
/**
* Get the names of all flags set.
*
* @return {string[]} Flag names
*/
OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
// This may be called before the constructor, thus before this.flags is set
return Object.keys( this.flags || {} );
};
/**
* Clear all flags.
*
* @chainable
* @fires flag
*/
OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
var flag, className,
changes = {},
remove = [],
classPrefix = 'oo-ui-flaggedElement-';
for ( flag in this.flags ) {
className = classPrefix + flag;
changes[ flag ] = false;
delete this.flags[ flag ];
remove.push( className );
}
if ( this.$flagged ) {
this.$flagged.removeClass( remove.join( ' ' ) );
}
this.updateThemeClasses();
this.emit( 'flag', changes );
return this;
};
/**
* Add one or more flags.
*
* @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
* or an object keyed by flag name with a boolean value that indicates whether the flag should
* be added (`true`) or removed (`false`).
* @chainable
* @fires flag
*/
OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
var i, len, flag, className,
changes = {},
add = [],
remove = [],
classPrefix = 'oo-ui-flaggedElement-';
if ( typeof flags === 'string' ) {
className = classPrefix + flags;
// Set
if ( !this.flags[ flags ] ) {
this.flags[ flags ] = true;
add.push( className );
}
} else if ( Array.isArray( flags ) ) {
for ( i = 0, len = flags.length; i < len; i++ ) {
flag = flags[ i ];
className = classPrefix + flag;
// Set
if ( !this.flags[ flag ] ) {
changes[ flag ] = true;
this.flags[ flag ] = true;
add.push( className );
}
}
} else if ( OO.isPlainObject( flags ) ) {
for ( flag in flags ) {
className = classPrefix + flag;
if ( flags[ flag ] ) {
// Set
if ( !this.flags[ flag ] ) {
changes[ flag ] = true;
this.flags[ flag ] = true;
add.push( className );
}
} else {
// Remove
if ( this.flags[ flag ] ) {
changes[ flag ] = false;
delete this.flags[ flag ];
remove.push( className );
}
}
}
}
if ( this.$flagged ) {
this.$flagged
.addClass( add.join( ' ' ) )
.removeClass( remove.join( ' ' ) );
}
this.updateThemeClasses();
this.emit( 'flag', changes );
return this;
};
/**
* TitledElement is mixed into other classes to provide a `title` attribute.
* Titles are rendered by the browser and are made visible when the user moves
* the mouse over the element. Titles are not visible on touch devices.
*
* @example
* // TitledElement provides a 'title' attribute to the
* // ButtonWidget class
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Title',
* title: 'I am a button'
* } );
* $( 'body' ).append( button.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
* If this config is omitted, the title functionality is applied to $element, the
* element created by the class.
* @cfg {string|Function} [title] The title text or a function that returns text. If
* this config is omitted, the value of the {@link #static-title static title} property is used.
*/
OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$titled = null;
this.title = null;
// Initialization
this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
this.setTitledElement( config.$titled || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* The title text, a function that returns text, or `null` for no title. The value of the static property
* is overridden if the #title config option is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.TitledElement.static.title = null;
/* Methods */
/**
* Set the titled element.
*
* This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
* If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
*
* @param {jQuery} $titled Element that should use the 'titled' functionality
*/
OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
if ( this.$titled ) {
this.$titled.removeAttr( 'title' );
}
this.$titled = $titled;
if ( this.title ) {
this.$titled.attr( 'title', this.title );
}
};
/**
* Set title.
*
* @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
* @chainable
*/
OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
title = ( typeof title === 'string' && title.length ) ? title : null;
if ( this.title !== title ) {
if ( this.$titled ) {
if ( title !== null ) {
this.$titled.attr( 'title', title );
} else {
this.$titled.removeAttr( 'title' );
}
}
this.title = title;
}
return this;
};
/**
* Get title.
*
* @return {string} Title string
*/
OO.ui.mixin.TitledElement.prototype.getTitle = function () {
return this.title;
};
/**
* AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
* Accesskeys allow an user to go to a specific element by using
* a shortcut combination of a browser specific keys + the key
* set to the field.
*
* @example
* // AccessKeyedElement provides an 'accesskey' attribute to the
* // ButtonWidget class
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Accesskey',
* accessKey: 'k'
* } );
* $( 'body' ).append( button.$element );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
* If this config is omitted, the accesskey functionality is applied to $element, the
* element created by the class.
* @cfg {string|Function} [accessKey] The key or a function that returns the key. If
* this config is omitted, no accesskey will be added.
*/
OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$accessKeyed = null;
this.accessKey = null;
// Initialization
this.setAccessKey( config.accessKey || null );
this.setAccessKeyedElement( config.$accessKeyed || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* The access key, a function that returns a key, or `null` for no accesskey.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
/* Methods */
/**
* Set the accesskeyed element.
*
* This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
* If an element is already set, the mixin's effect on that element is removed before the new element is set up.
*
* @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
*/
OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
if ( this.$accessKeyed ) {
this.$accessKeyed.removeAttr( 'accesskey' );
}
this.$accessKeyed = $accessKeyed;
if ( this.accessKey ) {
this.$accessKeyed.attr( 'accesskey', this.accessKey );
}
};
/**
* Set accesskey.
*
* @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
* @chainable
*/
OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
if ( this.accessKey !== accessKey ) {
if ( this.$accessKeyed ) {
if ( accessKey !== null ) {
this.$accessKeyed.attr( 'accesskey', accessKey );
} else {
this.$accessKeyed.removeAttr( 'accesskey' );
}
}
this.accessKey = accessKey;
}
return this;
};
/**
* Get accesskey.
*
* @return {string} accessKey string
*/
OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
return this.accessKey;
};
/**
* ButtonWidget is a generic widget for buttons. A wide variety of looks,
* feels, and functionality can be customized via the class’s configuration options
* and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
*
* @example
* // A button widget
* var button = new OO.ui.ButtonWidget( {
* label: 'Button with Icon',
* icon: 'remove',
* iconTitle: 'Remove'
* } );
* $( 'body' ).append( button.$element );
*
* NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [active=false] Whether button should be shown as active
* @cfg {string} [href] Hyperlink to visit when the button is clicked.
* @cfg {string} [target] The frame or window in which to open the hyperlink.
* @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
*/
OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ButtonWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, config );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
// Properties
this.href = null;
this.target = null;
this.noFollow = false;
// Events
this.connect( this, { disable: 'onDisable' } );
// Initialization
this.$button.append( this.$icon, this.$label, this.$indicator );
this.$element
.addClass( 'oo-ui-buttonWidget' )
.append( this.$button );
this.setActive( config.active );
this.setHref( config.href );
this.setTarget( config.target );
this.setNoFollow( config.noFollow );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
/* Methods */
/**
* Get hyperlink location.
*
* @return {string} Hyperlink location
*/
OO.ui.ButtonWidget.prototype.getHref = function () {
return this.href;
};
/**
* Get hyperlink target.
*
* @return {string} Hyperlink target
*/
OO.ui.ButtonWidget.prototype.getTarget = function () {
return this.target;
};
/**
* Get search engine traversal hint.
*
* @return {boolean} Whether search engines should avoid traversing this hyperlink
*/
OO.ui.ButtonWidget.prototype.getNoFollow = function () {
return this.noFollow;
};
/**
* Set hyperlink location.
*
* @param {string|null} href Hyperlink location, null to remove
*/
OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
href = typeof href === 'string' ? href : null;
if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
href = './' + href;
}
if ( href !== this.href ) {
this.href = href;
this.updateHref();
}
return this;
};
/**
* Update the `href` attribute, in case of changes to href or
* disabled state.
*
* @private
* @chainable
*/
OO.ui.ButtonWidget.prototype.updateHref = function () {
if ( this.href !== null && !this.isDisabled() ) {
this.$button.attr( 'href', this.href );
} else {
this.$button.removeAttr( 'href' );
}
return this;
};
/**
* Handle disable events.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.ButtonWidget.prototype.onDisable = function () {
this.updateHref();
};
/**
* Set hyperlink target.
*
* @param {string|null} target Hyperlink target, null to remove
*/
OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
target = typeof target === 'string' ? target : null;
if ( target !== this.target ) {
this.target = target;
if ( target !== null ) {
this.$button.attr( 'target', target );
} else {
this.$button.removeAttr( 'target' );
}
}
return this;
};
/**
* Set search engine traversal hint.
*
* @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
*/
OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
noFollow = typeof noFollow === 'boolean' ? noFollow : true;
if ( noFollow !== this.noFollow ) {
this.noFollow = noFollow;
if ( noFollow ) {
this.$button.attr( 'rel', 'nofollow' );
} else {
this.$button.removeAttr( 'rel' );
}
}
return this;
};
// Override method visibility hints from ButtonElement
/**
* @method setActive
*/
/**
* @method isActive
*/
/**
* A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
* its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
* removed, and cleared from the group.
*
* @example
* // Example: A ButtonGroupWidget with two buttons
* var button1 = new OO.ui.PopupButtonWidget( {
* label: 'Select a category',
* icon: 'menu',
* popup: {
* $content: $( '<p>List of categories...</p>' ),
* padded: true,
* align: 'left'
* }
* } );
* var button2 = new OO.ui.ButtonWidget( {
* label: 'Add item'
* });
* var buttonGroup = new OO.ui.ButtonGroupWidget( {
* items: [button1, button2]
* } );
* $( 'body' ).append( buttonGroup.$element );
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
*/
OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ButtonGroupWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-buttonGroupWidget' );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
/**
* IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
* which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
* for a list of icons included in the library.
*
* @example
* // An icon widget with a label
* var myIcon = new OO.ui.IconWidget( {
* icon: 'help',
* iconTitle: 'Help'
* } );
* // Create a label.
* var iconLabel = new OO.ui.LabelWidget( {
* label: 'Help'
* } );
* $( 'body' ).append( myIcon.$element, iconLabel.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.FlaggedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IconWidget = function OoUiIconWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IconWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-iconWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.IconWidget.static.tagName = 'span';
/**
* IndicatorWidgets create indicators, which are small graphics that are generally used to draw
* attention to the status of an item or to clarify the function of a control. For a list of
* indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example of an indicator widget
* var indicator1 = new OO.ui.IndicatorWidget( {
* indicator: 'alert'
* } );
*
* // Create a fieldset layout to add a label
* var fieldset = new OO.ui.FieldsetLayout();
* fieldset.addItems( [
* new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IndicatorWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-indicatorWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.IndicatorWidget.static.tagName = 'span';
/**
* LabelWidgets help identify the function of interface elements. Each LabelWidget can
* be configured with a `label` option that is set to a string, a label node, or a function:
*
* - String: a plaintext string
* - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
* label that includes a link or special styling, such as a gray color or additional graphical elements.
* - Function: a function that will produce a string in the future. Functions are used
* in cases where the value of the label is not currently defined.
*
* In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
* will come into focus when the label is clicked.
*
* @example
* // Examples of LabelWidgets
* var label1 = new OO.ui.LabelWidget( {
* label: 'plaintext label'
* } );
* var label2 = new OO.ui.LabelWidget( {
* label: $( '<a href="default.html">jQuery label</a>' )
* } );
* // Create a fieldset layout with fields for each example
* var fieldset = new OO.ui.FieldsetLayout();
* fieldset.addItems( [
* new OO.ui.FieldLayout( label1 ),
* new OO.ui.FieldLayout( label2 )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
* Clicking the label will focus the specified input field.
*/
OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.LabelWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
OO.ui.mixin.TitledElement.call( this, config );
// Properties
this.input = config.input;
// Initialization
if ( this.input instanceof OO.ui.InputWidget ) {
if ( this.input.getInputId() ) {
this.$element.attr( 'for', this.input.getInputId() );
}
}
this.$element.addClass( 'oo-ui-labelWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.LabelWidget.static.tagName = 'label';
/**
* PendingElement is a mixin that is used to create elements that notify users that something is happening
* and that they should wait before proceeding. The pending state is visually represented with a pending
* texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
* field of a {@link OO.ui.TextInputWidget text input widget}.
*
* Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
* used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
* in process dialogs.
*
* @example
* function MessageDialog( config ) {
* MessageDialog.parent.call( this, config );
* }
* OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
*
* MessageDialog.static.name = 'myMessageDialog';
* MessageDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MessageDialog.prototype.initialize = function () {
* MessageDialog.parent.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
* this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
* this.$body.append( this.content.$element );
* };
* MessageDialog.prototype.getBodyHeight = function () {
* return 100;
* }
* MessageDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action === 'save' ) {
* dialog.getActions().get({actions: 'save'})[0].pushPending();
* return new OO.ui.Process()
* .next( 1000 )
* .next( function () {
* dialog.getActions().get({actions: 'save'})[0].popPending();
* } );
* }
* return MessageDialog.parent.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* var dialog = new MessageDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
*/
OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.pending = 0;
this.$pending = null;
// Initialisation
this.setPendingElement( config.$pending || this.$element );
};
/* Setup */
OO.initClass( OO.ui.mixin.PendingElement );
/* Methods */
/**
* Set the pending element (and clean up any existing one).
*
* @param {jQuery} $pending The element to set to pending.
*/
OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
if ( this.$pending ) {
this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
}
this.$pending = $pending;
if ( this.pending > 0 ) {
this.$pending.addClass( 'oo-ui-pendingElement-pending' );
}
};
/**
* Check if an element is pending.
*
* @return {boolean} Element is pending
*/
OO.ui.mixin.PendingElement.prototype.isPending = function () {
return !!this.pending;
};
/**
* Increase the pending counter. The pending state will remain active until the counter is zero
* (i.e., the number of calls to #pushPending and #popPending is the same).
*
* @chainable
*/
OO.ui.mixin.PendingElement.prototype.pushPending = function () {
if ( this.pending === 0 ) {
this.$pending.addClass( 'oo-ui-pendingElement-pending' );
this.updateThemeClasses();
}
this.pending++;
return this;
};
/**
* Decrease the pending counter. The pending state will remain active until the counter is zero
* (i.e., the number of calls to #pushPending and #popPending is the same).
*
* @chainable
*/
OO.ui.mixin.PendingElement.prototype.popPending = function () {
if ( this.pending === 1 ) {
this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
this.updateThemeClasses();
}
this.pending = Math.max( 0, this.pending - 1 );
return this;
};
/**
* Element that will stick under a specified container, even when it is inserted elsewhere in the
* document (for example, in a OO.ui.Window's $overlay).
*
* The elements's position is automatically calculated and maintained when window is resized or the
* page is scrolled. If you reposition the container manually, you have to call #position to make
* sure the element is still placed correctly.
*
* As positioning is only possible when both the element and the container are attached to the DOM
* and visible, it's only done after you call #togglePositioning. You might want to do this inside
* the #toggle method to display a floating popup, for example.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
* @cfg {jQuery} [$floatableContainer] Node to position below
*/
OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$floatable = null;
this.$floatableContainer = null;
this.$floatableWindow = null;
this.$floatableClosestScrollable = null;
this.onFloatableScrollHandler = this.position.bind( this );
this.onFloatableWindowResizeHandler = this.position.bind( this );
// Initialization
this.setFloatableContainer( config.$floatableContainer );
this.setFloatableElement( config.$floatable || this.$element );
};
/* Methods */
/**
* Set floatable element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $floatable Element to make floatable
*/
OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
if ( this.$floatable ) {
this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
this.$floatable.css( { left: '', top: '' } );
}
this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
this.position();
};
/**
* Set floatable container.
*
* The element will be always positioned under the specified container.
*
* @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
*/
OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
this.$floatableContainer = $floatableContainer;
if ( this.$floatable ) {
this.position();
}
};
/**
* Toggle positioning.
*
* Do not turn positioning on until after the element is attached to the DOM and visible.
*
* @param {boolean} [positioning] Enable positioning, omit to toggle
* @chainable
*/
OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
var closestScrollableOfContainer;
if ( !this.$floatable || !this.$floatableContainer ) {
return this;
}
positioning = positioning === undefined ? !this.positioning : !!positioning;
if ( this.positioning !== positioning ) {
this.positioning = positioning;
closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
this.needsCustomPosition = !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] );
// If the scrollable is the root, we have to listen to scroll events
// on the window because of browser inconsistencies.
if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
}
if ( positioning ) {
this.$floatableWindow = $( this.getElementWindow() );
this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
this.$floatableClosestScrollable = $( closestScrollableOfContainer );
this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
// Initial position after visible
this.position();
} else {
if ( this.$floatableWindow ) {
this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
this.$floatableWindow = null;
}
if ( this.$floatableClosestScrollable ) {
this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
this.$floatableClosestScrollable = null;
}
this.$floatable.css( { left: '', right: '', top: '' } );
}
}
return this;
};
/**
* Check whether the bottom edge of the given element is within the viewport of the given container.
*
* @private
* @param {jQuery} $element
* @param {jQuery} $container
* @return {boolean}
*/
OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
var elemRect, contRect,
leftEdgeInBounds = false,
bottomEdgeInBounds = false,
rightEdgeInBounds = false;
elemRect = $element[ 0 ].getBoundingClientRect();
if ( $container[ 0 ] === window ) {
contRect = {
top: 0,
left: 0,
right: document.documentElement.clientWidth,
bottom: document.documentElement.clientHeight
};
} else {
contRect = $container[ 0 ].getBoundingClientRect();
}
// For completeness, if we still cared about topEdgeInBounds, that'd be:
// elemRect.top >= contRect.top && elemRect.top <= contRect.bottom
if ( elemRect.left >= contRect.left && elemRect.left <= contRect.right ) {
leftEdgeInBounds = true;
}
if ( elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom ) {
bottomEdgeInBounds = true;
}
if ( elemRect.right >= contRect.left && elemRect.right <= contRect.right ) {
rightEdgeInBounds = true;
}
// We only care that any part of the bottom edge is visible
return bottomEdgeInBounds && ( leftEdgeInBounds || rightEdgeInBounds );
};
/**
* Position the floatable below its container.
*
* This should only be done when both of them are attached to the DOM and visible.
*
* @chainable
*/
OO.ui.mixin.FloatableElement.prototype.position = function () {
var pos;
if ( !this.positioning ) {
return this;
}
if ( !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) {
this.$floatable.addClass( 'oo-ui-element-hidden' );
return;
} else {
this.$floatable.removeClass( 'oo-ui-element-hidden' );
}
if ( !this.needsCustomPosition ) {
return;
}
pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
// Position under container
pos.top += this.$floatableContainer.height();
// In LTR, we position from the left, and pos.left is already set
// In RTL, we position from the right instead.
if ( this.$floatableContainer.css( 'direction' ) === 'rtl' ) {
pos.right = this.$floatable.offsetParent().width() - pos.left - this.$floatableContainer.outerWidth();
delete pos.left;
}
this.$floatable.css( pos );
// We updated the position, so re-evaluate the clipping state.
// (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
// will not notice the need to update itself.)
// TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
// it not listen to the right events in the right places?
if ( this.clip ) {
this.clip();
}
return this;
};
/**
* Element that can be automatically clipped to visible boundaries.
*
* Whenever the element's natural height changes, you have to call
* {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
* clipping correctly.
*
* The dimensions of #$clippableContainer will be compared to the boundaries of the
* nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
* then #$clippable will be given a fixed reduced height and/or width and will be made
* scrollable. By default, #$clippable and #$clippableContainer are the same element,
* but you can build a static footer by setting #$clippableContainer to an element that contains
* #$clippable and the footer.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
* @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
* omit to use #$clippable
*/
OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$clippable = null;
this.$clippableContainer = null;
this.clipping = false;
this.clippedHorizontally = false;
this.clippedVertically = false;
this.$clippableScrollableContainer = null;
this.$clippableScroller = null;
this.$clippableWindow = null;
this.idealWidth = null;
this.idealHeight = null;
this.onClippableScrollHandler = this.clip.bind( this );
this.onClippableWindowResizeHandler = this.clip.bind( this );
// Initialization
if ( config.$clippableContainer ) {
this.setClippableContainer( config.$clippableContainer );
}
this.setClippableElement( config.$clippable || this.$element );
};
/* Methods */
/**
* Set clippable element.
*
* If an element is already set, it will be cleaned up before setting up the new element.
*
* @param {jQuery} $clippable Element to make clippable
*/
OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
if ( this.$clippable ) {
this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
}
this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
this.clip();
};
/**
* Set clippable container.
*
* This is the container that will be measured when deciding whether to clip. When clipping,
* #$clippable will be resized in order to keep the clippable container fully visible.
*
* If the clippable container is unset, #$clippable will be used.
*
* @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
*/
OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
this.$clippableContainer = $clippableContainer;
if ( this.$clippable ) {
this.clip();
}
};
/**
* Toggle clipping.
*
* Do not turn clipping on until after the element is attached to the DOM and visible.
*
* @param {boolean} [clipping] Enable clipping, omit to toggle
* @chainable
*/
OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
clipping = clipping === undefined ? !this.clipping : !!clipping;
if ( this.clipping !== clipping ) {
this.clipping = clipping;
if ( clipping ) {
this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
// If the clippable container is the root, we have to listen to scroll events and check
// jQuery.scrollTop on the window because of browser inconsistencies
this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
$( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
this.$clippableScrollableContainer;
this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
this.$clippableWindow = $( this.getElementWindow() )
.on( 'resize', this.onClippableWindowResizeHandler );
// Initial clip after visible
this.clip();
} else {
this.$clippable.css( {
width: '',
height: '',
maxWidth: '',
maxHeight: '',
overflowX: '',
overflowY: ''
} );
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
this.$clippableScrollableContainer = null;
this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
this.$clippableScroller = null;
this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
this.$clippableWindow = null;
}
}
return this;
};
/**
* Check if the element will be clipped to fit the visible area of the nearest scrollable container.
*
* @return {boolean} Element will be clipped to the visible area
*/
OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
return this.clipping;
};
/**
* Check if the bottom or right of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
return this.clippedHorizontally || this.clippedVertically;
};
/**
* Check if the right of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
return this.clippedHorizontally;
};
/**
* Check if the bottom of the element is being clipped by the nearest scrollable container.
*
* @return {boolean} Part of the element is being clipped
*/
OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
return this.clippedVertically;
};
/**
* Set the ideal size. These are the dimensions the element will have when it's not being clipped.
*
* @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
* @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
*/
OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
this.idealWidth = width;
this.idealHeight = height;
if ( !this.clipping ) {
// Update dimensions
this.$clippable.css( { width: width, height: height } );
}
// While clipping, idealWidth and idealHeight are not considered
};
/**
* Clip element to visible boundaries and allow scrolling when needed. You should call this method
* when the element's natural height changes.
*
* Element will be clipped the bottom or right of the element is within 10px of the edge of, or
* overlapped by, the visible area of the nearest scrollable container.
*
* Because calling clip() when the natural height changes isn't always possible, we also set
* max-height when the element isn't being clipped. This means that if the element tries to grow
* beyond the edge, something reasonable will happen before clip() is called.
*
* @chainable
*/
OO.ui.mixin.ClippableElement.prototype.clip = function () {
var $container, extraHeight, extraWidth, ccOffset,
$scrollableContainer, scOffset, scHeight, scWidth,
ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
desiredWidth, desiredHeight, allotedWidth, allotedHeight,
naturalWidth, naturalHeight, clipWidth, clipHeight,
buffer = 7; // Chosen by fair dice roll
if ( !this.clipping ) {
// this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
return this;
}
$container = this.$clippableContainer || this.$clippable;
extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
ccOffset = $container.offset();
if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
$scrollableContainer = this.$clippableWindow;
scOffset = { top: 0, left: 0 };
} else {
$scrollableContainer = this.$clippableScrollableContainer;
scOffset = $scrollableContainer.offset();
}
scHeight = $scrollableContainer.innerHeight() - buffer;
scWidth = $scrollableContainer.innerWidth() - buffer;
ccWidth = $container.outerWidth() + buffer;
scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
desiredWidth = ccOffset.left < 0 ?
ccWidth + ccOffset.left :
( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
// It should never be desirable to exceed the dimensions of the browser viewport... right?
desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth );
desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight );
allotedWidth = Math.ceil( desiredWidth - extraWidth );
allotedHeight = Math.ceil( desiredHeight - extraHeight );
naturalWidth = this.$clippable.prop( 'scrollWidth' );
naturalHeight = this.$clippable.prop( 'scrollHeight' );
clipWidth = allotedWidth < naturalWidth;
clipHeight = allotedHeight < naturalHeight;
if ( clipWidth ) {
// The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
// Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
this.$clippable.css( 'overflowX', 'scroll' );
void this.$clippable[ 0 ].offsetHeight; // Force reflow
this.$clippable.css( {
width: Math.max( 0, allotedWidth ),
maxWidth: ''
} );
} else {
this.$clippable.css( {
overflowX: '',
width: this.idealWidth ? this.idealWidth - extraWidth : '',
maxWidth: Math.max( 0, allotedWidth )
} );
}
if ( clipHeight ) {
// The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
// Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
this.$clippable.css( 'overflowY', 'scroll' );
void this.$clippable[ 0 ].offsetHeight; // Force reflow
this.$clippable.css( {
height: Math.max( 0, allotedHeight ),
maxHeight: ''
} );
} else {
this.$clippable.css( {
overflowY: '',
height: this.idealHeight ? this.idealHeight - extraHeight : '',
maxHeight: Math.max( 0, allotedHeight )
} );
}
// If we stopped clipping in at least one of the dimensions
if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
}
this.clippedHorizontally = clipWidth;
this.clippedVertically = clipHeight;
return this;
};
/**
* PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
* By default, each popup has an anchor that points toward its origin.
* Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
*
* @example
* // A popup widget.
* var popup = new OO.ui.PopupWidget( {
* $content: $( '<p>Hi there!</p>' ),
* padded: true,
* width: 300
* } );
*
* $( 'body' ).append( popup.$element );
* // To display the popup, toggle the visibility to 'true'.
* popup.toggle( true );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.ClippableElement
* @mixins OO.ui.mixin.FloatableElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number} [width=320] Width of popup in pixels
* @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
* @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
* @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
* If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
* popup is leaning towards the right of the screen.
* Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
* in the given language, which means it will flip to the correct positioning in right-to-left languages.
* Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
* sentence in the given language.
* @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
* See the [OOjs UI docs on MediaWiki][3] for an example.
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
* @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
* @cfg {jQuery} [$content] Content to append to the popup's body
* @cfg {jQuery} [$footer] Content to append to the popup's footer
* @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
* @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
* This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
* @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
* button.
* @cfg {boolean} [padded=false] Add padding to the popup's body
*/
OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.PopupWidget.parent.call( this, config );
// Properties (must be set before ClippableElement constructor call)
this.$body = $( '<div>' );
this.$popup = $( '<div>' );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
$clippable: this.$body,
$clippableContainer: this.$popup
} ) );
OO.ui.mixin.FloatableElement.call( this, config );
// Properties
this.$anchor = $( '<div>' );
// If undefined, will be computed lazily in updateDimensions()
this.$container = config.$container;
this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
this.autoClose = !!config.autoClose;
this.$autoCloseIgnore = config.$autoCloseIgnore;
this.transitionTimeout = null;
this.anchor = null;
this.width = config.width !== undefined ? config.width : 320;
this.height = config.height !== undefined ? config.height : null;
this.setAlignment( config.align );
this.onMouseDownHandler = this.onMouseDown.bind( this );
this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
// Initialization
this.toggleAnchor( config.anchor === undefined || config.anchor );
this.$body.addClass( 'oo-ui-popupWidget-body' );
this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
this.$popup
.addClass( 'oo-ui-popupWidget-popup' )
.append( this.$body );
this.$element
.addClass( 'oo-ui-popupWidget' )
.append( this.$popup, this.$anchor );
// Move content, which was added to #$element by OO.ui.Widget, to the body
// FIXME This is gross, we should use '$body' or something for the config
if ( config.$content instanceof jQuery ) {
this.$body.append( config.$content );
}
if ( config.padded ) {
this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
}
if ( config.head ) {
this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
this.$head = $( '<div>' )
.addClass( 'oo-ui-popupWidget-head' )
.append( this.$label, this.closeButton.$element );
this.$popup.prepend( this.$head );
}
if ( config.$footer ) {
this.$footer = $( '<div>' )
.addClass( 'oo-ui-popupWidget-footer' )
.append( config.$footer );
this.$popup.append( this.$footer );
}
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
/* Methods */
/**
* Handles mouse down events.
*
* @private
* @param {MouseEvent} e Mouse down event
*/
OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
if (
this.isVisible() &&
!OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
) {
this.toggle( false );
}
};
/**
* Bind mouse down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
// Capture clicks outside popup
this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
};
/**
* Handles close button click events.
*
* @private
*/
OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
if ( this.isVisible() ) {
this.toggle( false );
}
};
/**
* Unbind mouse down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
};
/**
* Handles key down events.
*
* @private
* @param {KeyboardEvent} e Key down event
*/
OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
if (
e.which === OO.ui.Keys.ESCAPE &&
this.isVisible()
) {
this.toggle( false );
e.preventDefault();
e.stopPropagation();
}
};
/**
* Bind key down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
/**
* Unbind key down listener.
*
* @private
*/
OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
};
/**
* Show, hide, or toggle the visibility of the anchor.
*
* @param {boolean} [show] Show anchor, omit to toggle
*/
OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
show = show === undefined ? !this.anchored : !!show;
if ( this.anchored !== show ) {
if ( show ) {
this.$element.addClass( 'oo-ui-popupWidget-anchored' );
} else {
this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
}
this.anchored = show;
}
};
/**
* Check if the anchor is visible.
*
* @return {boolean} Anchor is visible
*/
OO.ui.PopupWidget.prototype.hasAnchor = function () {
return this.anchor;
};
/**
* @inheritdoc
*/
OO.ui.PopupWidget.prototype.toggle = function ( show ) {
var change;
show = show === undefined ? !this.isVisible() : !!show;
change = show !== this.isVisible();
// Parent method
OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
if ( change ) {
this.togglePositioning( show && !!this.$floatableContainer );
if ( show ) {
if ( this.autoClose ) {
this.bindMouseDownListener();
this.bindKeyDownListener();
}
this.updateDimensions();
this.toggleClipping( true );
} else {
this.toggleClipping( false );
if ( this.autoClose ) {
this.unbindMouseDownListener();
this.unbindKeyDownListener();
}
}
}
return this;
};
/**
* Set the size of the popup.
*
* Changing the size may also change the popup's position depending on the alignment.
*
* @param {number} width Width in pixels
* @param {number} height Height in pixels
* @param {boolean} [transition=false] Use a smooth transition
* @chainable
*/
OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
this.width = width;
this.height = height !== undefined ? height : null;
if ( this.isVisible() ) {
this.updateDimensions( transition );
}
};
/**
* Update the size and position.
*
* Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
* be called automatically.
*
* @param {boolean} [transition=false] Use a smooth transition
* @chainable
*/
OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth, direction,
dirFactor, align,
alignMap = {
ltr: {
'force-left': 'backwards',
'force-right': 'forwards'
},
rtl: {
'force-left': 'forwards',
'force-right': 'backwards'
}
},
widget = this;
if ( !this.$container ) {
// Lazy-initialize $container if not specified in constructor
this.$container = $( this.getClosestScrollableElementContainer() );
}
direction = this.$container.css( 'direction' );
dirFactor = direction === 'rtl' ? -1 : 1;
align = alignMap[ direction ][ this.align ] || this.align;
// Set height and width before measuring things, since it might cause our measurements
// to change (e.g. due to scrollbars appearing or disappearing)
this.$popup.css( {
width: this.width,
height: this.height !== null ? this.height : 'auto'
} );
// Compute initial popupOffset based on alignment
popupOffset = this.width * ( { backwards: -1, center: -0.5, forwards: 0 } )[ align ];
// Figure out if this will cause the popup to go beyond the edge of the container
originOffset = this.$element.offset().left;
containerLeft = this.$container.offset().left;
containerWidth = this.$container.innerWidth();
containerRight = containerLeft + containerWidth;
popupLeft = dirFactor * popupOffset - this.containerPadding;
popupRight = dirFactor * popupOffset + this.containerPadding + this.width + this.containerPadding;
overlapLeft = ( originOffset + popupLeft ) - containerLeft;
overlapRight = containerRight - ( originOffset + popupRight );
// Adjust offset to make the popup not go beyond the edge, if needed
if ( overlapRight < 0 ) {
popupOffset += dirFactor * overlapRight;
} else if ( overlapLeft < 0 ) {
popupOffset -= dirFactor * overlapLeft;
}
// Adjust offset to avoid anchor being rendered too close to the edge
// $anchor.width() doesn't work with the pure CSS anchor (returns 0)
// TODO: Find a measurement that works for CSS anchors and image anchors
anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
if ( popupOffset + this.width < anchorWidth ) {
popupOffset = anchorWidth - this.width;
} else if ( -popupOffset < anchorWidth ) {
popupOffset = -anchorWidth;
}
// Prevent transition from being interrupted
clearTimeout( this.transitionTimeout );
if ( transition ) {
// Enable transition
this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
}
// Position body relative to anchor
this.$popup.css( direction === 'rtl' ? 'margin-right' : 'margin-left', popupOffset );
if ( transition ) {
// Prevent transitioning after transition is complete
this.transitionTimeout = setTimeout( function () {
widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
}, 200 );
} else {
// Prevent transitioning immediately
this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
}
// Reevaluate clipping state since we've relocated and resized the popup
this.clip();
return this;
};
/**
* Set popup alignment
*
* @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
* `backwards` or `forwards`.
*/
OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
// Transform values deprecated since v0.11.0
if ( align === 'left' || align === 'right' ) {
OO.ui.warnDeprecation( 'PopupWidget#setAlignment parameter value `' + align + '` is deprecated. Use `force-right` or `force-left` instead.' );
align = { left: 'force-right', right: 'force-left' }[ align ];
}
// Validate alignment
if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
this.align = align;
} else {
this.align = 'center';
}
};
/**
* Get popup alignment
*
* @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
* `backwards` or `forwards`.
*/
OO.ui.PopupWidget.prototype.getAlignment = function () {
return this.align;
};
/**
* PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
* A popup is a container for content. It is overlaid and positioned absolutely. By default, each
* popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
* See {@link OO.ui.PopupWidget PopupWidget} for an example.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [popup] Configuration to pass to popup
* @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
*/
OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.popup = new OO.ui.PopupWidget( $.extend(
{ autoClose: true },
config.popup,
{ $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore ) }
) );
};
/* Methods */
/**
* Get popup.
*
* @return {OO.ui.PopupWidget} Popup widget
*/
OO.ui.mixin.PopupElement.prototype.getPopup = function () {
return this.popup;
};
/**
* PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
* which is used to display additional information or options.
*
* @example
* // Example of a popup button.
* var popupButton = new OO.ui.PopupButtonWidget( {
* label: 'Popup button with options',
* icon: 'menu',
* popup: {
* $content: $( '<p>Additional options here.</p>' ),
* padded: true,
* align: 'force-left'
* }
* } );
* // Append the button to the DOM.
* $( 'body' ).append( popupButton.$element );
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PopupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
* the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the popup uses relative positioning.
*/
OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
// Parent constructor
OO.ui.PopupButtonWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PopupElement.call( this, $.extend( true, {}, config, {
popup: {
$floatableContainer: this.$element
}
} ) );
// Properties
this.$overlay = config.$overlay || this.$element;
// Events
this.connect( this, { click: 'onAction' } );
// Initialization
this.$element
.addClass( 'oo-ui-popupButtonWidget' )
.attr( 'aria-haspopup', 'true' );
this.popup.$element
.addClass( 'oo-ui-popupButtonWidget-popup' )
.toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
.toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
this.$overlay.append( this.popup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
/* Methods */
/**
* Handle the button action being triggered.
*
* @private
*/
OO.ui.PopupButtonWidget.prototype.onAction = function () {
this.popup.toggle();
};
/**
* Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
*
* Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
*
* @private
* @abstract
* @class
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
};
/* Setup */
OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
/* Methods */
/**
* Set the disabled state of the widget.
*
* This will also update the disabled state of child widgets.
*
* @param {boolean} disabled Disable widget
* @chainable
*/
OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
var i, len;
// Parent method
// Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
OO.ui.Widget.prototype.setDisabled.call( this, disabled );
// During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
if ( this.items ) {
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].updateDisabled();
}
}
return this;
};
/**
* Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
*
* Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
* allows bidirectional communication.
*
* Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
*
* @private
* @abstract
* @class
*
* @constructor
*/
OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
//
};
/* Methods */
/**
* Check if widget is disabled.
*
* Checks parent if present, making disabled state inheritable.
*
* @return {boolean} Widget is disabled
*/
OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
return this.disabled ||
( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
*/
OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
// Parent method
// Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
OO.ui.Element.prototype.setElementGroup.call( this, group );
// Initialize item disabled states
this.updateDisabled();
return this;
};
/**
* OptionWidgets are special elements that can be selected and configured with data. The
* data is often unique for each option, but it does not have to be. OptionWidgets are used
* with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
* and examples, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ItemWidget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.OptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ItemWidget.call( this );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.AccessKeyedElement.call( this, config );
// Properties
this.selected = false;
this.highlighted = false;
this.pressed = false;
// Initialization
this.$element
.data( 'oo-ui-optionWidget', this )
// Allow programmatic focussing (and by accesskey), but not tabbing
.attr( 'tabindex', '-1' )
.attr( 'role', 'option' )
.attr( 'aria-selected', 'false' )
.addClass( 'oo-ui-optionWidget' )
.append( this.$label );
};
/* Setup */
OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* Whether this option can be selected. See #setSelected.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.selectable = true;
/**
* Whether this option can be highlighted. See #setHighlighted.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.highlightable = true;
/**
* Whether this option can be pressed. See #setPressed.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.pressable = true;
/**
* Whether this option will be scrolled into view when it is selected.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
/* Methods */
/**
* Check if the option can be selected.
*
* @return {boolean} Item is selectable
*/
OO.ui.OptionWidget.prototype.isSelectable = function () {
return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
};
/**
* Check if the option can be highlighted. A highlight indicates that the option
* may be selected when a user presses enter or clicks. Disabled items cannot
* be highlighted.
*
* @return {boolean} Item is highlightable
*/
OO.ui.OptionWidget.prototype.isHighlightable = function () {
return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
};
/**
* Check if the option can be pressed. The pressed state occurs when a user mouses
* down on an item, but has not yet let go of the mouse.
*
* @return {boolean} Item is pressable
*/
OO.ui.OptionWidget.prototype.isPressable = function () {
return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
};
/**
* Check if the option is selected.
*
* @return {boolean} Item is selected
*/
OO.ui.OptionWidget.prototype.isSelected = function () {
return this.selected;
};
/**
* Check if the option is highlighted. A highlight indicates that the
* item may be selected when a user presses enter or clicks.
*
* @return {boolean} Item is highlighted
*/
OO.ui.OptionWidget.prototype.isHighlighted = function () {
return this.highlighted;
};
/**
* Check if the option is pressed. The pressed state occurs when a user mouses
* down on an item, but has not yet let go of the mouse. The item may appear
* selected, but it will not be selected until the user releases the mouse.
*
* @return {boolean} Item is pressed
*/
OO.ui.OptionWidget.prototype.isPressed = function () {
return this.pressed;
};
/**
* Set the option’s selected state. In general, all modifications to the selection
* should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Select option
* @chainable
*/
OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
if ( this.constructor.static.selectable ) {
this.selected = !!state;
this.$element
.toggleClass( 'oo-ui-optionWidget-selected', state )
.attr( 'aria-selected', state.toString() );
if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
this.scrollElementIntoView();
}
this.updateThemeClasses();
}
return this;
};
/**
* Set the option’s highlighted state. In general, all programmatic
* modifications to the highlight should be handled by the
* SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Highlight option
* @chainable
*/
OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
if ( this.constructor.static.highlightable ) {
this.highlighted = !!state;
this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
this.updateThemeClasses();
}
return this;
};
/**
* Set the option’s pressed state. In general, all
* programmatic modifications to the pressed state should be handled by the
* SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Press option
* @chainable
*/
OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
if ( this.constructor.static.pressable ) {
this.pressed = !!state;
this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
this.updateThemeClasses();
}
return this;
};
/**
* Get text to match search strings against.
*
* The default implementation returns the label text, but subclasses
* can override this to provide more complex behavior.
*
* @return {string|boolean} String to match search string against
*/
OO.ui.OptionWidget.prototype.getMatchText = function () {
var label = this.getLabel();
return typeof label === 'string' ? label : this.$label.text();
};
/**
* A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
* select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
* {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
* menu selects}.
*
* This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
* information, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example of a select widget with three options
* var select = new OO.ui.SelectWidget( {
* items: [
* new OO.ui.OptionWidget( {
* data: 'a',
* label: 'Option One',
* } ),
* new OO.ui.OptionWidget( {
* data: 'b',
* label: 'Option Two',
* } ),
* new OO.ui.OptionWidget( {
* data: 'c',
* label: 'Option Three',
* } )
* ]
* } );
* $( 'body' ).append( select.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
* Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
* the [OOjs UI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*/
OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.SelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Properties
this.pressed = false;
this.selecting = null;
this.onMouseUpHandler = this.onMouseUp.bind( this );
this.onMouseMoveHandler = this.onMouseMove.bind( this );
this.onKeyDownHandler = this.onKeyDown.bind( this );
this.onKeyPressHandler = this.onKeyPress.bind( this );
this.keyPressBuffer = '';
this.keyPressBufferTimer = null;
this.blockMouseOverEvents = 0;
// Events
this.connect( this, {
toggle: 'onToggle'
} );
this.$element.on( {
focusin: this.onFocus.bind( this ),
mousedown: this.onMouseDown.bind( this ),
mouseover: this.onMouseOver.bind( this ),
mouseleave: this.onMouseLeave.bind( this )
} );
// Initialization
this.$element
.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
.attr( 'role', 'listbox' );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
/* Events */
/**
* @event highlight
*
* A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
*
* @param {OO.ui.OptionWidget|null} item Highlighted item
*/
/**
* @event press
*
* A `press` event is emitted when the #pressItem method is used to programmatically modify the
* pressed state of an option.
*
* @param {OO.ui.OptionWidget|null} item Pressed item
*/
/**
* @event select
*
* A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
*
* @param {OO.ui.OptionWidget|null} item Selected item
*/
/**
* @event choose
* A `choose` event is emitted when an item is chosen with the #chooseItem method.
* @param {OO.ui.OptionWidget} item Chosen item
*/
/**
* @event add
*
* An `add` event is emitted when options are added to the select with the #addItems method.
*
* @param {OO.ui.OptionWidget[]} items Added items
* @param {number} index Index of insertion point
*/
/**
* @event remove
*
* A `remove` event is emitted when options are removed from the select with the #clearItems
* or #removeItems methods.
*
* @param {OO.ui.OptionWidget[]} items Removed items
*/
/* Methods */
/**
* Handle focus events
*
* @private
* @param {jQuery.Event} event
*/
OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
var item;
if ( event.target === this.$element[ 0 ] ) {
// This widget was focussed, e.g. by the user tabbing to it.
// The styles for focus state depend on one of the items being selected.
if ( !this.getSelectedItem() ) {
item = this.getFirstSelectableItem();
}
} else {
// One of the options got focussed (and the event bubbled up here).
// They can't be tabbed to, but they can be activated using accesskeys.
item = this.getTargetItem( event );
}
if ( item ) {
if ( item.constructor.static.highlightable ) {
this.highlightItem( item );
} else {
this.selectItem( item );
}
}
if ( event.target !== this.$element[ 0 ] ) {
this.$element.focus();
}
};
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
var item;
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
this.togglePressed( true );
item = this.getTargetItem( e );
if ( item && item.isSelectable() ) {
this.pressItem( item );
this.selecting = item;
this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
}
}
return false;
};
/**
* Handle mouse up events.
*
* @private
* @param {MouseEvent} e Mouse up event
*/
OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
var item;
this.togglePressed( false );
if ( !this.selecting ) {
item = this.getTargetItem( e );
if ( item && item.isSelectable() ) {
this.selecting = item;
}
}
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
this.pressItem( null );
this.chooseItem( this.selecting );
this.selecting = null;
}
this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
return false;
};
/**
* Handle mouse move events.
*
* @private
* @param {MouseEvent} e Mouse move event
*/
OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
var item;
if ( !this.isDisabled() && this.pressed ) {
item = this.getTargetItem( e );
if ( item && item !== this.selecting && item.isSelectable() ) {
this.pressItem( item );
this.selecting = item;
}
}
};
/**
* Handle mouse over events.
*
* @private
* @param {jQuery.Event} e Mouse over event
*/
OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
var item;
if ( this.blockMouseOverEvents ) {
return;
}
if ( !this.isDisabled() ) {
item = this.getTargetItem( e );
this.highlightItem( item && item.isHighlightable() ? item : null );
}
return false;
};
/**
* Handle mouse leave events.
*
* @private
* @param {jQuery.Event} e Mouse over event
*/
OO.ui.SelectWidget.prototype.onMouseLeave = function () {
if ( !this.isDisabled() ) {
this.highlightItem( null );
}
return false;
};
/**
* Handle key down events.
*
* @protected
* @param {KeyboardEvent} e Key down event
*/
OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
var nextItem,
handled = false,
currentItem = this.getHighlightedItem() || this.getSelectedItem();
if ( !this.isDisabled() && this.isVisible() ) {
switch ( e.keyCode ) {
case OO.ui.Keys.ENTER:
if ( currentItem && currentItem.constructor.static.highlightable ) {
// Was only highlighted, now let's select it. No-op if already selected.
this.chooseItem( currentItem );
handled = true;
}
break;
case OO.ui.Keys.UP:
case OO.ui.Keys.LEFT:
this.clearKeyPressBuffer();
nextItem = this.getRelativeSelectableItem( currentItem, -1 );
handled = true;
break;
case OO.ui.Keys.DOWN:
case OO.ui.Keys.RIGHT:
this.clearKeyPressBuffer();
nextItem = this.getRelativeSelectableItem( currentItem, 1 );
handled = true;
break;
case OO.ui.Keys.ESCAPE:
case OO.ui.Keys.TAB:
if ( currentItem && currentItem.constructor.static.highlightable ) {
currentItem.setHighlighted( false );
}
this.unbindKeyDownListener();
this.unbindKeyPressListener();
// Don't prevent tabbing away / defocusing
handled = false;
break;
}
if ( nextItem ) {
if ( nextItem.constructor.static.highlightable ) {
this.highlightItem( nextItem );
} else {
this.chooseItem( nextItem );
}
this.scrollItemIntoView( nextItem );
}
if ( handled ) {
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Bind key down listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
};
/**
* Unbind key down listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
};
/**
* Scroll item into view, preventing spurious mouse highlight actions from happening.
*
* @param {OO.ui.OptionWidget} item Item to scroll into view
*/
OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
var widget = this;
// Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
// and around 100-150 ms after it is finished.
this.blockMouseOverEvents++;
item.scrollElementIntoView().done( function () {
setTimeout( function () {
widget.blockMouseOverEvents--;
}, 200 );
} );
};
/**
* Clear the key-press buffer
*
* @protected
*/
OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
if ( this.keyPressBufferTimer ) {
clearTimeout( this.keyPressBufferTimer );
this.keyPressBufferTimer = null;
}
this.keyPressBuffer = '';
};
/**
* Handle key press events.
*
* @protected
* @param {KeyboardEvent} e Key press event
*/
OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
var c, filter, item;
if ( !e.charCode ) {
if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
return false;
}
return;
}
if ( String.fromCodePoint ) {
c = String.fromCodePoint( e.charCode );
} else {
c = String.fromCharCode( e.charCode );
}
if ( this.keyPressBufferTimer ) {
clearTimeout( this.keyPressBufferTimer );
}
this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
item = this.getHighlightedItem() || this.getSelectedItem();
if ( this.keyPressBuffer === c ) {
// Common (if weird) special case: typing "xxxx" will cycle through all
// the items beginning with "x".
if ( item ) {
item = this.getRelativeSelectableItem( item, 1 );
}
} else {
this.keyPressBuffer += c;
}
filter = this.getItemMatcher( this.keyPressBuffer, false );
if ( !item || !filter( item ) ) {
item = this.getRelativeSelectableItem( item, 1, filter );
}
if ( item ) {
if ( this.isVisible() && item.constructor.static.highlightable ) {
this.highlightItem( item );
} else {
this.chooseItem( item );
}
this.scrollItemIntoView( item );
}
e.preventDefault();
e.stopPropagation();
};
/**
* Get a matcher for the specific string
*
* @protected
* @param {string} s String to match against items
* @param {boolean} [exact=false] Only accept exact matches
* @return {Function} function ( OO.ui.OptionWidget ) => boolean
*/
OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
var re;
if ( s.normalize ) {
s = s.normalize();
}
s = exact ? s.trim() : s.replace( /^\s+/, '' );
re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
if ( exact ) {
re += '\\s*$';
}
re = new RegExp( re, 'i' );
return function ( item ) {
var matchText = item.getMatchText();
if ( matchText.normalize ) {
matchText = matchText.normalize();
}
return re.test( matchText );
};
};
/**
* Bind key press listener.
*
* @protected
*/
OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
};
/**
* Unbind key down listener.
*
* If you override this, be sure to call this.clearKeyPressBuffer() from your
* implementation.
*
* @protected
*/
OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
this.clearKeyPressBuffer();
};
/**
* Visibility change handler
*
* @protected
* @param {boolean} visible
*/
OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
if ( !visible ) {
this.clearKeyPressBuffer();
}
};
/**
* Get the closest item to a jQuery.Event.
*
* @private
* @param {jQuery.Event} e
* @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
*/
OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
};
/**
* Get selected item.
*
* @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
*/
OO.ui.SelectWidget.prototype.getSelectedItem = function () {
var i, len;
for ( i = 0, len = this.items.length; i < len; i++ ) {
if ( this.items[ i ].isSelected() ) {
return this.items[ i ];
}
}
return null;
};
/**
* Get highlighted item.
*
* @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
*/
OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
var i, len;
for ( i = 0, len = this.items.length; i < len; i++ ) {
if ( this.items[ i ].isHighlighted() ) {
return this.items[ i ];
}
}
return null;
};
/**
* Toggle pressed state.
*
* Press is a state that occurs when a user mouses down on an item, but
* has not yet let go of the mouse. The item may appear selected, but it will not be selected
* until the user releases the mouse.
*
* @param {boolean} pressed An option is being pressed
*/
OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
if ( pressed === undefined ) {
pressed = !this.pressed;
}
if ( pressed !== this.pressed ) {
this.$element
.toggleClass( 'oo-ui-selectWidget-pressed', pressed )
.toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
this.pressed = pressed;
}
};
/**
* Highlight an option. If the `item` param is omitted, no options will be highlighted
* and any existing highlight will be removed. The highlight is mutually exclusive.
*
* @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
* @fires highlight
* @chainable
*/
OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
var i, len, highlighted,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
highlighted = this.items[ i ] === item;
if ( this.items[ i ].isHighlighted() !== highlighted ) {
this.items[ i ].setHighlighted( highlighted );
changed = true;
}
}
if ( changed ) {
this.emit( 'highlight', item );
}
return this;
};
/**
* Fetch an item by its label.
*
* @param {string} label Label of the item to select.
* @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
* @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
*/
OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
var i, item, found,
len = this.items.length,
filter = this.getItemMatcher( label, true );
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
return item;
}
}
if ( prefix ) {
found = null;
filter = this.getItemMatcher( label, false );
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
if ( found ) {
return null;
}
found = item;
}
}
if ( found ) {
return found;
}
}
return null;
};
/**
* Programmatically select an option by its label. If the item does not exist,
* all options will be deselected.
*
* @param {string} [label] Label of the item to select.
* @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
* @fires select
* @chainable
*/
OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
var itemFromLabel = this.getItemFromLabel( label, !!prefix );
if ( label === undefined || !itemFromLabel ) {
return this.selectItem();
}
return this.selectItem( itemFromLabel );
};
/**
* Programmatically select an option by its data. If the `data` parameter is omitted,
* or if the item does not exist, all options will be deselected.
*
* @param {Object|string} [data] Value of the item to select, omit to deselect all
* @fires select
* @chainable
*/
OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
var itemFromData = this.getItemFromData( data );
if ( data === undefined || !itemFromData ) {
return this.selectItem();
}
return this.selectItem( itemFromData );
};
/**
* Programmatically select an option by its reference. If the `item` parameter is omitted,
* all options will be deselected.
*
* @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
* @fires select
* @chainable
*/
OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
var i, len, selected,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
selected = this.items[ i ] === item;
if ( this.items[ i ].isSelected() !== selected ) {
this.items[ i ].setSelected( selected );
changed = true;
}
}
if ( changed ) {
this.emit( 'select', item );
}
return this;
};
/**
* Press an item.
*
* Press is a state that occurs when a user mouses down on an item, but has not
* yet let go of the mouse. The item may appear selected, but it will not be selected until the user
* releases the mouse.
*
* @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
* @fires press
* @chainable
*/
OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
var i, len, pressed,
changed = false;
for ( i = 0, len = this.items.length; i < len; i++ ) {
pressed = this.items[ i ] === item;
if ( this.items[ i ].isPressed() !== pressed ) {
this.items[ i ].setPressed( pressed );
changed = true;
}
}
if ( changed ) {
this.emit( 'press', item );
}
return this;
};
/**
* Choose an item.
*
* Note that ‘choose’ should never be modified programmatically. A user can choose
* an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
* use the #selectItem method.
*
* This method is identical to #selectItem, but may vary in subclasses that take additional action
* when users choose an item with the keyboard or mouse.
*
* @param {OO.ui.OptionWidget} item Item to choose
* @fires choose
* @chainable
*/
OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
if ( item ) {
this.selectItem( item );
this.emit( 'choose', item );
}
return this;
};
/**
* Get an option by its position relative to the specified item (or to the start of the option array,
* if item is `null`). The direction in which to search through the option array is specified with a
* number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
* `null` if there are no options in the array.
*
* @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
* @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
* @param {Function} [filter] Only consider items for which this function returns
* true. Function takes an OO.ui.OptionWidget and returns a boolean.
* @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
*/
OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
var currentIndex, nextIndex, i,
increase = direction > 0 ? 1 : -1,
len = this.items.length;
if ( item instanceof OO.ui.OptionWidget ) {
currentIndex = this.items.indexOf( item );
nextIndex = ( currentIndex + increase + len ) % len;
} else {
// If no item is selected and moving forward, start at the beginning.
// If moving backward, start at the end.
nextIndex = direction > 0 ? 0 : len - 1;
}
for ( i = 0; i < len; i++ ) {
item = this.items[ nextIndex ];
if (
item instanceof OO.ui.OptionWidget && item.isSelectable() &&
( !filter || filter( item ) )
) {
return item;
}
nextIndex = ( nextIndex + increase + len ) % len;
}
return null;
};
/**
* Get the next selectable item or `null` if there are no selectable items.
* Disabled options and menu-section markers and breaks are not selectable.
*
* @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
*/
OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
return this.getRelativeSelectableItem( null, 1 );
};
/**
* Add an array of options to the select. Optionally, an index number can be used to
* specify an insertion point.
*
* @param {OO.ui.OptionWidget[]} items Items to add
* @param {number} [index] Index to insert items after
* @fires add
* @chainable
*/
OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
// Mixin method
OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
// Always provide an index, even if it was omitted
this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
return this;
};
/**
* Remove the specified array of options from the select. Options will be detached
* from the DOM, not removed, so they can be reused later. To remove all options from
* the select, you may wish to use the #clearItems method instead.
*
* @param {OO.ui.OptionWidget[]} items Items to remove
* @fires remove
* @chainable
*/
OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
var i, len, item;
// Deselect items being removed
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.isSelected() ) {
this.selectItem( null );
}
}
// Mixin method
OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
this.emit( 'remove', items );
return this;
};
/**
* Clear all options from the select. Options will be detached from the DOM, not removed,
* so that they can be reused later. To remove a subset of options from the select, use
* the #removeItems method.
*
* @fires remove
* @chainable
*/
OO.ui.SelectWidget.prototype.clearItems = function () {
var items = this.items.slice();
// Mixin method
OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
// Clear selection
this.selectItem( null );
this.emit( 'remove', items );
return this;
};
/**
* DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
* with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
* This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
* options. For more information about options and selects, please see the
* [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Decorated options in a select widget
* var select = new OO.ui.SelectWidget( {
* items: [
* new OO.ui.DecoratedOptionWidget( {
* data: 'a',
* label: 'Option with icon',
* icon: 'help'
* } ),
* new OO.ui.DecoratedOptionWidget( {
* data: 'b',
* label: 'Option with indicator',
* indicator: 'next'
* } )
* ]
* } );
* $( 'body' ).append( select.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.OptionWidget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
// Parent constructor
OO.ui.DecoratedOptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-decoratedOptionWidget' )
.prepend( this.$icon )
.append( this.$indicator );
};
/* Setup */
OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
/**
* MenuOptionWidget is an option widget that looks like a menu item. The class is used with
* OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
* the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.DecoratedOptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
// Configuration initialization
config = $.extend( { icon: 'check' }, config );
// Parent constructor
OO.ui.MenuOptionWidget.parent.call( this, config );
// Initialization
this.$element
.attr( 'role', 'menuitem' )
.addClass( 'oo-ui-menuOptionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
/**
* MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
* {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
*
* @example
* var myDropdown = new OO.ui.DropdownWidget( {
* menu: {
* items: [
* new OO.ui.MenuSectionOptionWidget( {
* label: 'Dogs'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'corgi',
* label: 'Welsh Corgi'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'poodle',
* label: 'Standard Poodle'
* } ),
* new OO.ui.MenuSectionOptionWidget( {
* label: 'Cats'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'lion',
* label: 'Lion'
* } )
* ]
* }
* } );
* $( 'body' ).append( myDropdown.$element );
*
* @class
* @extends OO.ui.DecoratedOptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
// Parent constructor
OO.ui.MenuSectionOptionWidget.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuSectionOptionWidget.static.selectable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.MenuSectionOptionWidget.static.highlightable = false;
/**
* MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
* is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
* See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
* and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
* MenuSelectWidgets themselves are not instantiated directly, rather subclassed
* and customized to be opened, closed, and displayed as needed.
*
* By default, menus are clipped to the visible viewport and are not visible when a user presses the
* mouse outside the menu.
*
* Menus also have support for keyboard interaction:
*
* - Enter/Return key: choose and select a menu option
* - Up-arrow key: highlight the previous menu option
* - Down-arrow key: highlight the next menu option
* - Esc key: hide the menu
*
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.ClippableElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
* the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
* and {@link OO.ui.mixin.LookupElement LookupElement}
* @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
* the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
* @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
* anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
* that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
* that button, unless the button (or its parent widget) is passed in here.
* @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
* @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
*/
OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MenuSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
// Properties
this.autoHide = config.autoHide === undefined || !!config.autoHide;
this.filterFromInput = !!config.filterFromInput;
this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
this.$widget = config.widget ? config.widget.$element : null;
this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
// Initialization
this.$element
.addClass( 'oo-ui-menuSelectWidget' )
.attr( 'role', 'menu' );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
/* Methods */
/**
* Handles document mouse down events.
*
* @protected
* @param {MouseEvent} e Mouse down event
*/
OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
if (
!OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
) {
this.toggle( false );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
var currentItem = this.getHighlightedItem() || this.getSelectedItem();
if ( !this.isDisabled() && this.isVisible() ) {
switch ( e.keyCode ) {
case OO.ui.Keys.LEFT:
case OO.ui.Keys.RIGHT:
// Do nothing if a text field is associated, arrow keys will be handled natively
if ( !this.$input ) {
OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
}
break;
case OO.ui.Keys.ESCAPE:
case OO.ui.Keys.TAB:
if ( currentItem ) {
currentItem.setHighlighted( false );
}
this.toggle( false );
// Don't prevent tabbing away, prevent defocusing
if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
e.preventDefault();
e.stopPropagation();
}
break;
default:
OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
return;
}
}
};
/**
* Update menu item visibility after input changes.
*
* @protected
*/
OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
var i, item, visible,
anyVisible = false,
len = this.items.length,
showAll = !this.isVisible(),
filter = showAll ? null : this.getItemMatcher( this.$input.val() );
for ( i = 0; i < len; i++ ) {
item = this.items[ i ];
if ( item instanceof OO.ui.OptionWidget ) {
visible = showAll || filter( item );
anyVisible = anyVisible || visible;
item.toggle( visible );
}
}
this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
// Reevaluate clipping
this.clip();
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
if ( this.$input ) {
this.$input.on( 'keydown', this.onKeyDownHandler );
} else {
OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
if ( this.$input ) {
this.$input.off( 'keydown', this.onKeyDownHandler );
} else {
OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
if ( this.$input ) {
if ( this.filterFromInput ) {
this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
}
} else {
OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
}
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
if ( this.$input ) {
if ( this.filterFromInput ) {
this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
this.updateItemVisibility();
}
} else {
OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
}
};
/**
* Choose an item.
*
* When a user chooses an item, the menu is closed.
*
* Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
* or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
*
* @param {OO.ui.OptionWidget} item Item to choose
* @chainable
*/
OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
this.toggle( false );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
// Reevaluate clipping
this.clip();
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
// Reevaluate clipping
this.clip();
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.clearItems = function () {
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
// Reevaluate clipping
this.clip();
return this;
};
/**
* @inheritdoc
*/
OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
var change;
visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
change = visible !== this.isVisible();
// Parent method
OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
if ( change ) {
if ( visible ) {
this.bindKeyDownListener();
this.bindKeyPressListener();
this.toggleClipping( true );
if ( this.getSelectedItem() ) {
this.getSelectedItem().scrollElementIntoView( { duration: 0 } );
}
// Auto-hide
if ( this.autoHide ) {
this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
}
} else {
this.unbindKeyDownListener();
this.unbindKeyPressListener();
this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
this.toggleClipping( false );
}
}
return this;
};
/**
* DropdownWidgets are not menus themselves, rather they contain a menu of options created with
* OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
* users can interact with it.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.DropdownInputWidget instead.
*
* @example
* // Example: A DropdownWidget with a menu that contains three options
* var dropDown = new OO.ui.DropdownWidget( {
* label: 'Dropdown menu: Select a menu option',
* menu: {
* items: [
* new OO.ui.MenuOptionWidget( {
* data: 'a',
* label: 'First'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'b',
* label: 'Second'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'c',
* label: 'Third'
* } )
* ]
* }
* } );
*
* $( 'body' ).append( dropDown.$element );
*
* dropDown.getMenu().selectItemByData( 'b' );
*
* dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
*
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
* @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
* the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the menu uses relative positioning.
*/
OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
// Configuration initialization
config = $.extend( { indicator: 'down' }, config );
// Parent constructor
OO.ui.DropdownWidget.parent.call( this, config );
// Properties (must be set before TabIndexedElement constructor call)
this.$handle = this.$( '<span>' );
this.$overlay = config.$overlay || this.$element;
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
// Properties
this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
widget: this,
$container: this.$element
}, config.menu ) );
// Events
this.$handle.on( {
click: this.onClick.bind( this ),
keydown: this.onKeyDown.bind( this ),
// Hack? Handle type-to-search when menu is not expanded and not handling its own events
keypress: this.menu.onKeyPressHandler,
blur: this.menu.clearKeyPressBuffer.bind( this.menu )
} );
this.menu.connect( this, {
select: 'onMenuSelect',
toggle: 'onMenuToggle'
} );
// Initialization
this.$handle
.addClass( 'oo-ui-dropdownWidget-handle' )
.append( this.$icon, this.$label, this.$indicator );
this.$element
.addClass( 'oo-ui-dropdownWidget' )
.append( this.$handle );
this.$overlay.append( this.menu.$element );
};
/* Setup */
OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Get the menu.
*
* @return {OO.ui.MenuSelectWidget} Menu of widget
*/
OO.ui.DropdownWidget.prototype.getMenu = function () {
return this.menu;
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.MenuOptionWidget} item Selected menu item
*/
OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
var selectedLabel;
if ( !item ) {
this.setLabel( null );
return;
}
selectedLabel = item.getLabel();
// If the label is a DOM element, clone it, because setLabel will append() it
if ( selectedLabel instanceof jQuery ) {
selectedLabel = selectedLabel.clone();
}
this.setLabel( selectedLabel );
};
/**
* Handle menu toggle events.
*
* @private
* @param {boolean} isVisible Menu toggle event
*/
OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
};
/**
* Handle mouse click events.
*
* @private
* @param {jQuery.Event} e Mouse click event
*/
OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
this.menu.toggle();
}
return false;
};
/**
* Handle key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
if (
!this.isDisabled() &&
(
e.which === OO.ui.Keys.ENTER ||
(
!this.menu.isVisible() &&
(
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.UP ||
e.which === OO.ui.Keys.DOWN
)
)
)
) {
this.menu.toggle();
return false;
}
};
/**
* RadioOptionWidget is an option widget that looks like a radio button.
* The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
*
* @class
* @extends OO.ui.OptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
// Parent constructor
OO.ui.RadioOptionWidget.parent.call( this, config );
// Initialization
// Remove implicit role, we're handling it ourselves
this.radio.$input.attr( 'role', 'presentation' );
this.$element
.addClass( 'oo-ui-radioOptionWidget' )
.attr( 'role', 'radio' )
.attr( 'aria-checked', 'false' )
.removeAttr( 'aria-selected' )
.prepend( this.radio.$element );
};
/* Setup */
OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.highlightable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.pressable = false;
/**
* @static
* @inheritdoc
*/
OO.ui.RadioOptionWidget.static.tagName = 'label';
/* Methods */
/**
* @inheritdoc
*/
OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
this.radio.setSelected( state );
this.$element
.attr( 'aria-checked', state.toString() )
.removeAttr( 'aria-selected' );
return this;
};
/**
* @inheritdoc
*/
OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
this.radio.setDisabled( this.isDisabled() );
return this;
};
/**
* RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
* options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
* an interface for adding, removing and selecting options.
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.RadioSelectInputWidget instead.
*
* @example
* // A RadioSelectWidget with RadioOptions.
* var option1 = new OO.ui.RadioOptionWidget( {
* data: 'a',
* label: 'Selected radio option'
* } );
*
* var option2 = new OO.ui.RadioOptionWidget( {
* data: 'b',
* label: 'Unselected radio option'
* } );
*
* var radioSelect=new OO.ui.RadioSelectWidget( {
* items: [ option1, option2 ]
* } );
*
* // Select 'option 1' using the RadioSelectWidget's selectItem() method.
* radioSelect.selectItem( option1 );
*
* $( 'body' ).append( radioSelect.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
// Parent constructor
OO.ui.RadioSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.$element.on( {
focus: this.bindKeyDownListener.bind( this ),
blur: this.unbindKeyDownListener.bind( this )
} );
// Initialization
this.$element
.addClass( 'oo-ui-radioSelectWidget' )
.attr( 'role', 'radiogroup' );
};
/* Setup */
OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
/**
* MultioptionWidgets are special elements that can be selected and configured with data. The
* data is often unique for each option, but it does not have to be. MultioptionWidgets are used
* with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
* and examples, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ItemWidget
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Whether the option is initially selected
*/
OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MultioptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ItemWidget.call( this );
OO.ui.mixin.LabelElement.call( this, config );
// Properties
this.selected = null;
// Initialization
this.$element
.addClass( 'oo-ui-multioptionWidget' )
.append( this.$label );
this.setSelected( config.selected );
};
/* Setup */
OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
/* Events */
/**
* @event change
*
* A change event is emitted when the selected state of the option changes.
*
* @param {boolean} selected Whether the option is now selected
*/
/* Methods */
/**
* Check if the option is selected.
*
* @return {boolean} Item is selected
*/
OO.ui.MultioptionWidget.prototype.isSelected = function () {
return this.selected;
};
/**
* Set the option’s selected state. In general, all modifications to the selection
* should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
* method instead of this method.
*
* @param {boolean} [state=false] Select option
* @chainable
*/
OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
state = !!state;
if ( this.selected !== state ) {
this.selected = state;
this.emit( 'change', state );
this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
}
return this;
};
/**
* MultiselectWidget allows selecting multiple options from a list.
*
* For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @abstract
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
*/
OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
// Parent constructor
OO.ui.MultiselectWidget.parent.call( this, config );
// Configuration initialization
config = config || {};
// Mixin constructors
OO.ui.mixin.GroupWidget.call( this, config );
// Events
this.aggregate( { change: 'select' } );
// This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
// by GroupElement only when items are added/removed
this.connect( this, { select: [ 'emit', 'change' ] } );
// Initialization
if ( config.items ) {
this.addItems( config.items );
}
this.$group.addClass( 'oo-ui-multiselectWidget-group' );
this.$element.addClass( 'oo-ui-multiselectWidget' )
.append( this.$group );
};
/* Setup */
OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
/* Events */
/**
* @event change
*
* A change event is emitted when the set of items changes, or an item is selected or deselected.
*/
/**
* @event select
*
* A select event is emitted when an item is selected or deselected.
*/
/* Methods */
/**
* Get options that are selected.
*
* @return {OO.ui.MultioptionWidget[]} Selected options
*/
OO.ui.MultiselectWidget.prototype.getSelectedItems = function () {
return this.items.filter( function ( item ) {
return item.isSelected();
} );
};
/**
* Get the data of options that are selected.
*
* @return {Object[]|string[]} Values of selected options
*/
OO.ui.MultiselectWidget.prototype.getSelectedItemsData = function () {
return this.getSelectedItems().map( function ( item ) {
return item.data;
} );
};
/**
* Select options by reference. Options not mentioned in the `items` array will be deselected.
*
* @param {OO.ui.MultioptionWidget[]} items Items to select
* @chainable
*/
OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
this.items.forEach( function ( item ) {
var selected = items.indexOf( item ) !== -1;
item.setSelected( selected );
} );
return this;
};
/**
* Select items by their data. Options not mentioned in the `datas` array will be deselected.
*
* @param {Object[]|string[]} datas Values of items to select
* @chainable
*/
OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
var items,
widget = this;
items = datas.map( function ( data ) {
return widget.getItemFromData( data );
} );
this.selectItems( items );
return this;
};
/**
* CheckboxMultioptionWidget is an option widget that looks like a checkbox.
* The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
*
* @class
* @extends OO.ui.MultioptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.checkbox = new OO.ui.CheckboxInputWidget();
// Parent constructor
OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
// Events
this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultioptionWidget' )
.prepend( this.checkbox.$element );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
/* Methods */
/**
* Handle checkbox selected state change.
*
* @private
*/
OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
this.setSelected( this.checkbox.isSelected() );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
this.checkbox.setSelected( state );
return this;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
this.checkbox.setDisabled( this.isDisabled() );
return this;
};
/**
* Focus the widget.
*/
OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
this.checkbox.focus();
};
/**
* Handle key down events.
*
* @protected
* @param {jQuery.Event} e
*/
OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
var
element = this.getElementGroup(),
nextItem;
if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
nextItem = element.getRelativeFocusableItem( this, -1 );
} else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
nextItem = element.getRelativeFocusableItem( this, 1 );
}
if ( nextItem ) {
e.preventDefault();
nextItem.focus();
}
};
/**
* CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
* checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
* CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
*
* If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
* OO.ui.CheckboxMultiselectInputWidget instead.
*
* @example
* // A CheckboxMultiselectWidget with CheckboxMultioptions.
* var option1 = new OO.ui.CheckboxMultioptionWidget( {
* data: 'a',
* selected: true,
* label: 'Selected checkbox'
* } );
*
* var option2 = new OO.ui.CheckboxMultioptionWidget( {
* data: 'b',
* label: 'Unselected checkbox'
* } );
*
* var multiselect=new OO.ui.CheckboxMultiselectWidget( {
* items: [ option1, option2 ]
* } );
*
* $( 'body' ).append( multiselect.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.MultiselectWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
// Parent constructor
OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
// Properties
this.$lastClicked = null;
// Events
this.$group.on( 'click', this.onClick.bind( this ) );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultiselectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
/* Methods */
/**
* Get an option by its position relative to the specified item (or to the start of the option array,
* if item is `null`). The direction in which to search through the option array is specified with a
* number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
* `null` if there are no options in the array.
*
* @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
* @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
* @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
*/
OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
var currentIndex, nextIndex, i,
increase = direction > 0 ? 1 : -1,
len = this.items.length;
if ( item ) {
currentIndex = this.items.indexOf( item );
nextIndex = ( currentIndex + increase + len ) % len;
} else {
// If no item is selected and moving forward, start at the beginning.
// If moving backward, start at the end.
nextIndex = direction > 0 ? 0 : len - 1;
}
for ( i = 0; i < len; i++ ) {
item = this.items[ nextIndex ];
if ( item && !item.isDisabled() ) {
return item;
}
nextIndex = ( nextIndex + increase + len ) % len;
}
return null;
};
/**
* Handle click events on checkboxes.
*
* @param {jQuery.Event} e
*/
OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
$lastClicked = this.$lastClicked,
$nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
.not( '.oo-ui-widget-disabled' );
// Allow selecting multiple options at once by Shift-clicking them
if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
$options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
lastClickedIndex = $options.index( $lastClicked );
nowClickedIndex = $options.index( $nowClicked );
// If it's the same item, either the user is being silly, or it's a fake event generated by the
// browser. In either case we don't need custom handling.
if ( nowClickedIndex !== lastClickedIndex ) {
items = this.items;
wasSelected = items[ nowClickedIndex ].isSelected();
direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
// This depends on the DOM order of the items and the order of the .items array being the same.
for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
if ( !items[ i ].isDisabled() ) {
items[ i ].setSelected( !wasSelected );
}
}
// For the now-clicked element, use immediate timeout to allow the browser to do its own
// handling first, then set our value. The order in which events happen is different for
// clicks on the <input> and on the <label> and there are additional fake clicks fired for
// non-click actions that change the checkboxes.
e.preventDefault();
setTimeout( function () {
if ( !items[ nowClickedIndex ].isDisabled() ) {
items[ nowClickedIndex ].setSelected( !wasSelected );
}
} );
}
}
if ( $nowClicked.length ) {
this.$lastClicked = $nowClicked;
}
};
/**
* FloatingMenuSelectWidget is a menu that will stick under a specified
* container, even when it is inserted elsewhere in the document (for example,
* in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
* menu from being clipped too aggresively.
*
* The menu's position is automatically calculated and maintained when the menu
* is toggled or the window is resized.
*
* See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
*
* @class
* @extends OO.ui.MenuSelectWidget
* @mixins OO.ui.mixin.FloatableElement
*
* @constructor
* @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
* Deprecated, omit this parameter and specify `$container` instead.
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
*/
OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
// Allow 'inputWidget' parameter and config for backwards compatibility
if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
config = inputWidget;
inputWidget = config.inputWidget;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
// Properties (must be set before mixin constructors)
this.inputWidget = inputWidget; // For backwards compatibility
this.$container = config.$container || this.inputWidget.$element;
// Mixins constructors
OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
// Initialization
this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
// For backwards compatibility
this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
/* Methods */
/**
* @inheritdoc
*/
OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
var change;
visible = visible === undefined ? !this.isVisible() : !!visible;
change = visible !== this.isVisible();
if ( change && visible ) {
// Make sure the width is set before the parent method runs.
this.setIdealSize( this.$container.width() );
}
// Parent method
// This will call this.clip(), which is nonsensical since we're not positioned yet...
OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
if ( change ) {
this.togglePositioning( this.isVisible() );
}
return this;
};
/*
* The old name for the FloatingMenuSelectWidget widget, provided for backwards-compatibility.
*
* @class
* @extends OO.ui.FloatingMenuSelectWidget
*
* @constructor
* @deprecated since v0.12.5.
*/
OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget() {
OO.ui.warnDeprecation( 'TextInputMenuSelectWidget is deprecated. Use the FloatingMenuSelectWidget instead.' );
// Parent constructor
OO.ui.TextInputMenuSelectWidget.parent.apply( this, arguments );
};
OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.FloatingMenuSelectWidget );
/**
* Progress bars visually display the status of an operation, such as a download,
* and can be either determinate or indeterminate:
*
* - **determinate** process bars show the percent of an operation that is complete.
*
* - **indeterminate** process bars use a visual display of motion to indicate that an operation
* is taking place. Because the extent of an indeterminate operation is unknown, the bar does
* not use percentages.
*
* The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
*
* @example
* // Examples of determinate and indeterminate progress bars.
* var progressBar1 = new OO.ui.ProgressBarWidget( {
* progress: 33
* } );
* var progressBar2 = new OO.ui.ProgressBarWidget();
*
* // Create a FieldsetLayout to layout progress bars
* var fieldset = new OO.ui.FieldsetLayout;
* fieldset.addItems( [
* new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
* new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
* ] );
* $( 'body' ).append( fieldset.$element );
*
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
* To create a determinate progress bar, specify a number that reflects the initial percent complete.
* By default, the progress bar is indeterminate.
*/
OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ProgressBarWidget.parent.call( this, config );
// Properties
this.$bar = $( '<div>' );
this.progress = null;
// Initialization
this.setProgress( config.progress !== undefined ? config.progress : false );
this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
this.$element
.attr( {
role: 'progressbar',
'aria-valuemin': 0,
'aria-valuemax': 100
} )
.addClass( 'oo-ui-progressBarWidget' )
.append( this.$bar );
};
/* Setup */
OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ProgressBarWidget.static.tagName = 'div';
/* Methods */
/**
* Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
*
* @return {number|boolean} Progress percent
*/
OO.ui.ProgressBarWidget.prototype.getProgress = function () {
return this.progress;
};
/**
* Set the percent of the process completed or `false` for an indeterminate process.
*
* @param {number|boolean} progress Progress percent or `false` for indeterminate
*/
OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
this.progress = progress;
if ( progress !== false ) {
this.$bar.css( 'width', this.progress + '%' );
this.$element.attr( 'aria-valuenow', this.progress );
} else {
this.$bar.css( 'width', '' );
this.$element.removeAttr( 'aria-valuenow' );
}
this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
};
/**
* InputWidget is the base class for all input widgets, which
* include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
* {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
* See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.AccessKeyedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
* @cfg {string} [value=''] The value of the input.
* @cfg {string} [dir] The directionality of the input (ltr/rtl).
* @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
* before it is accepted.
*/
OO.ui.InputWidget = function OoUiInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.InputWidget.parent.call( this, config );
// Properties
// See #reusePreInfuseDOM about config.$input
this.$input = config.$input || this.getInputElement( config );
this.value = '';
this.inputFilter = config.inputFilter;
// Mixin constructors
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
// Events
this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
// Initialization
this.$input
.addClass( 'oo-ui-inputWidget-input' )
.attr( 'name', config.name )
.prop( 'disabled', this.isDisabled() );
this.$element
.addClass( 'oo-ui-inputWidget' )
.append( this.$input );
this.setValue( config.value );
if ( config.dir ) {
this.setDir( config.dir );
}
};
/* Setup */
OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.InputWidget.static.supportsSimpleLabel = true;
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
// Reusing $input lets browsers preserve inputted values across page reloads (T114134)
config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
return config;
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
if ( config.$input && config.$input.length ) {
state.value = config.$input.val();
// Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
state.focus = config.$input.is( ':focus' );
}
return state;
};
/* Events */
/**
* @event change
*
* A change event is emitted when the value of the input changes.
*
* @param {string} value
*/
/* Methods */
/**
* Get input element.
*
* Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
* different circumstances. The element must have a `value` property (like form elements).
*
* @protected
* @param {Object} config Configuration options
* @return {jQuery} Input element
*/
OO.ui.InputWidget.prototype.getInputElement = function () {
return $( '<input>' );
};
/**
* Get input element's ID.
*
* If the element already has an ID then that is returned, otherwise unique ID is
* generated, set on the element, and returned.
*
* @return {string} The ID of the element
*/
OO.ui.InputWidget.prototype.getInputId = function () {
var id = this.$input.attr( 'id' );
if ( id === undefined ) {
id = OO.ui.generateElementId();
this.$input.attr( 'id', id );
}
return id;
};
/**
* Handle potentially value-changing events.
*
* @private
* @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
*/
OO.ui.InputWidget.prototype.onEdit = function () {
var widget = this;
if ( !this.isDisabled() ) {
// Allow the stack to clear so the value will be updated
setTimeout( function () {
widget.setValue( widget.$input.val() );
} );
}
};
/**
* Get the value of the input.
*
* @return {string} Input value
*/
OO.ui.InputWidget.prototype.getValue = function () {
// Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
// it, and we won't know unless they're kind enough to trigger a 'change' event.
var value = this.$input.val();
if ( this.value !== value ) {
this.setValue( value );
}
return this.value;
};
/**
* Set the directionality of the input.
*
* @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
* @chainable
*/
OO.ui.InputWidget.prototype.setDir = function ( dir ) {
this.$input.prop( 'dir', dir );
return this;
};
/**
* Set the value of the input.
*
* @param {string} value New value
* @fires change
* @chainable
*/
OO.ui.InputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
// Update the DOM if it has changed. Note that with cleanUpValue, it
// is possible for the DOM value to change without this.value changing.
if ( this.$input.val() !== value ) {
this.$input.val( value );
}
if ( this.value !== value ) {
this.value = value;
this.emit( 'change', this.value );
}
return this;
};
/**
* Clean up incoming value.
*
* Ensures value is a string, and converts undefined and null to empty string.
*
* @private
* @param {string} value Original value
* @return {string} Cleaned up value
*/
OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
if ( value === undefined || value === null ) {
return '';
} else if ( this.inputFilter ) {
return this.inputFilter( String( value ) );
} else {
return String( value );
}
};
/**
* Simulate the behavior of clicking on a label bound to this input. This method is only called by
* {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
* called directly.
*/
OO.ui.InputWidget.prototype.simulateLabelClick = function () {
OO.ui.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
if ( !this.isDisabled() ) {
if ( this.$input.is( ':checkbox, :radio' ) ) {
this.$input.click();
}
if ( this.$input.is( ':input' ) ) {
this.$input[ 0 ].focus();
}
}
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
if ( this.$input ) {
this.$input.prop( 'disabled', this.isDisabled() );
}
return this;
};
/**
* Focus the input.
*
* @chainable
*/
OO.ui.InputWidget.prototype.focus = function () {
this.$input[ 0 ].focus();
return this;
};
/**
* Blur the input.
*
* @chainable
*/
OO.ui.InputWidget.prototype.blur = function () {
this.$input[ 0 ].blur();
return this;
};
/**
* @inheritdoc
*/
OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.value !== undefined && state.value !== this.getValue() ) {
this.setValue( state.value );
}
if ( state.focus ) {
this.focus();
}
};
/**
* ButtonInputWidget is used to submit HTML forms and is intended to be used within
* a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
* want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
* HTML `<button>` (the default) or an HTML `<input>` tags. See the
* [OOjs UI documentation on MediaWiki] [1] for more information.
*
* @example
* // A ButtonInputWidget rendered as an HTML button, the default.
* var button = new OO.ui.ButtonInputWidget( {
* label: 'Input button',
* icon: 'check',
* value: 'check'
* } );
* $( 'body' ).append( button.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
*
* @class
* @extends OO.ui.InputWidget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
* @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
* Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
* non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
* be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
*/
OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
// Configuration initialization
config = $.extend( { type: 'button', useInputTag: false }, config );
// See InputWidget#reusePreInfuseDOM about config.$input
if ( config.$input ) {
config.$input.empty();
}
// Properties (must be set before parent constructor, which calls #setValue)
this.useInputTag = config.useInputTag;
// Parent constructor
OO.ui.ButtonInputWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
// Initialization
if ( !config.useInputTag ) {
this.$input.append( this.$icon, this.$label, this.$indicator );
}
this.$element.addClass( 'oo-ui-buttonInputWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* Disable generating `<label>` elements for buttons. One would very rarely need additional label
* for a button, and it's already a big clickable target, and it causes unexpected rendering.
*
* @static
* @inheritdoc
*/
OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
var type;
type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
};
/**
* Set label value.
*
* If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
*
* @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
* text, or `null` for no label
* @chainable
*/
OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
if ( typeof label === 'function' ) {
label = OO.ui.resolveMsg( label );
}
if ( this.useInputTag ) {
// Discard non-plaintext labels
if ( typeof label !== 'string' ) {
label = '';
}
this.$input.val( label );
}
return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
};
/**
* Set the value of the input.
*
* This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
* they do not support {@link #value values}.
*
* @param {string} value New value
* @chainable
*/
OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
if ( !this.useInputTag ) {
OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
}
return this;
};
/**
* CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
* Note that these {@link OO.ui.InputWidget input widgets} are best laid out
* in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
* alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // An example of selected, unselected, and disabled checkbox inputs
* var checkbox1=new OO.ui.CheckboxInputWidget( {
* value: 'a',
* selected: true
* } );
* var checkbox2=new OO.ui.CheckboxInputWidget( {
* value: 'b'
* } );
* var checkbox3=new OO.ui.CheckboxInputWidget( {
* value:'c',
* disabled: true
* } );
* // Create a fieldset layout with fields for each checkbox.
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Checkboxes'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
* new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
* new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
*/
OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.CheckboxInputWidget.parent.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-checkboxInputWidget' )
// Required for pretty styling in MediaWiki theme
.append( $( '<span>' ) );
this.setSelected( config.selected !== undefined ? config.selected : false );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
state.checked = config.$input.prop( 'checked' );
return state;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'checkbox' );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
var widget = this;
if ( !this.isDisabled() ) {
// Allow the stack to clear so the value will be updated
setTimeout( function () {
widget.setSelected( widget.$input.prop( 'checked' ) );
} );
}
};
/**
* Set selection state of this checkbox.
*
* @param {boolean} state `true` for selected
* @chainable
*/
OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
state = !!state;
if ( this.selected !== state ) {
this.selected = state;
this.$input.prop( 'checked', this.selected );
this.emit( 'change', this.selected );
}
return this;
};
/**
* Check if this checkbox is selected.
*
* @return {boolean} Checkbox is selected
*/
OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
// Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
// it, and we won't know unless they're kind enough to trigger a 'change' event.
var selected = this.$input.prop( 'checked' );
if ( this.selected !== selected ) {
this.setSelected( selected );
}
return this.selected;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
this.setSelected( state.checked );
}
};
/**
* DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
* within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
* of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
* more information about input widgets.
*
* A DropdownInputWidget always has a value (one of the options is always selected), unless there
* are no options. If no `value` configuration option is provided, the first option is selected.
* If you need a state representing no value (no option being selected), use a DropdownWidget.
*
* This and OO.ui.RadioSelectInputWidget support the same configuration options.
*
* @example
* // Example: A DropdownInputWidget with three options
* var dropdownInput = new OO.ui.DropdownInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( dropdownInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
* @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
*/
OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
// Configuration initialization
config = config || {};
// See InputWidget#reusePreInfuseDOM about config.$input
if ( config.$input ) {
config.$input.addClass( 'oo-ui-element-hidden' );
}
// Properties (must be done before parent constructor which calls #setDisabled)
this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
// Parent constructor
OO.ui.DropdownInputWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TitledElement.call( this, config );
// Events
this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
// Initialization
this.setOptions( config.options || [] );
this.$element
.addClass( 'oo-ui-dropdownInputWidget' )
.append( this.dropdownWidget.$element );
};
/* Setup */
OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'hidden' );
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.MenuOptionWidget} item Selected menu item
*/
OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
this.setValue( item.getData() );
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
this.dropdownWidget.getMenu().selectItemByData( value );
OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
return this;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
this.dropdownWidget.setDisabled( state );
OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
* @chainable
*/
OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
var
value = this.getValue(),
widget = this;
// Rebuild the dropdown menu
this.dropdownWidget.getMenu()
.clearItems()
.addItems( options.map( function ( opt ) {
var optValue = widget.cleanUpValue( opt.data );
return new OO.ui.MenuOptionWidget( {
data: optValue,
label: opt.label !== undefined ? opt.label : optValue
} );
} ) );
// Restore the previous value, or reset to something sensible
if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
// Previous value is still available, ensure consistency with the dropdown
this.setValue( value );
} else {
// No longer valid, reset
if ( options.length ) {
this.setValue( options[ 0 ].data );
}
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.focus = function () {
this.dropdownWidget.getMenu().toggle( true );
return this;
};
/**
* @inheritdoc
*/
OO.ui.DropdownInputWidget.prototype.blur = function () {
this.dropdownWidget.getMenu().toggle( false );
return this;
};
/**
* RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
* in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
* with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
* please see the [OOjs UI documentation on MediaWiki][1].
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // An example of selected, unselected, and disabled radio inputs
* var radio1 = new OO.ui.RadioInputWidget( {
* value: 'a',
* selected: true
* } );
* var radio2 = new OO.ui.RadioInputWidget( {
* value: 'b'
* } );
* var radio3 = new OO.ui.RadioInputWidget( {
* value: 'c',
* disabled: true
* } );
* // Create a fieldset layout with fields for each radio button.
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Radio inputs'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
* new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
* new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
*/
OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.RadioInputWidget.parent.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-radioInputWidget' )
// Required for pretty styling in MediaWiki theme
.append( $( '<span>' ) );
this.setSelected( config.selected !== undefined ? config.selected : false );
};
/* Setup */
OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
state.checked = config.$input.prop( 'checked' );
return state;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.RadioInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'radio' );
};
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.prototype.onEdit = function () {
// RadioInputWidget doesn't track its state.
};
/**
* Set selection state of this radio button.
*
* @param {boolean} state `true` for selected
* @chainable
*/
OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
// RadioInputWidget doesn't track its state.
this.$input.prop( 'checked', state );
return this;
};
/**
* Check if this radio button is selected.
*
* @return {boolean} Radio is selected
*/
OO.ui.RadioInputWidget.prototype.isSelected = function () {
return this.$input.prop( 'checked' );
};
/**
* @inheritdoc
*/
OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
this.setSelected( state.checked );
}
};
/**
* RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
* within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
* of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
* more information about input widgets.
*
* This and OO.ui.DropdownInputWidget support the same configuration options.
*
* @example
* // Example: A RadioSelectInputWidget with three options
* var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( radioSelectInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
*/
OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.radioSelectWidget = new OO.ui.RadioSelectWidget();
// Parent constructor
OO.ui.RadioSelectInputWidget.parent.call( this, config );
// Events
this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
// Initialization
this.setOptions( config.options || [] );
this.$element
.addClass( 'oo-ui-radioSelectInputWidget' )
.append( this.radioSelectWidget.$element );
};
/* Setup */
OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
return state;
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
// Cannot reuse the `<input type=radio>` set
delete config.$input;
return config;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'hidden' );
};
/**
* Handles menu select events.
*
* @private
* @param {OO.ui.RadioOptionWidget} item Selected menu item
*/
OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
this.setValue( item.getData() );
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
this.radioSelectWidget.selectItemByData( value );
OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
return this;
};
/**
* @inheritdoc
*/
OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
this.radioSelectWidget.setDisabled( state );
OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
* @chainable
*/
OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
var
value = this.getValue(),
widget = this;
// Rebuild the radioSelect menu
this.radioSelectWidget
.clearItems()
.addItems( options.map( function ( opt ) {
var optValue = widget.cleanUpValue( opt.data );
return new OO.ui.RadioOptionWidget( {
data: optValue,
label: opt.label !== undefined ? opt.label : optValue
} );
} ) );
// Restore the previous value, or reset to something sensible
if ( this.radioSelectWidget.getItemFromData( value ) ) {
// Previous value is still available, ensure consistency with the radioSelect
this.setValue( value );
} else {
// No longer valid, reset
if ( options.length ) {
this.setValue( options[ 0 ].data );
}
}
return this;
};
/**
* CheckboxMultiselectInputWidget is a
* {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
* HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
* HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
* more information about input widgets.
*
* @example
* // Example: A CheckboxMultiselectInputWidget with three options
* var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
* options: [
* { data: 'a', label: 'First' },
* { data: 'b', label: 'Second'},
* { data: 'c', label: 'Third' }
* ]
* } );
* $( 'body' ).append( multiselectInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
*/
OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
// Configuration initialization
config = config || {};
// Properties (must be done before parent constructor which calls #setDisabled)
this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
// Parent constructor
OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
// Properties
this.inputName = config.name;
// Initialization
this.$element
.addClass( 'oo-ui-checkboxMultiselectInputWidget' )
.append( this.checkboxMultiselectWidget.$element );
// We don't use this.$input, but rather the CheckboxInputWidgets inside each option
this.$input.detach();
this.setOptions( config.options || [] );
// Have to repeat this from parent, as we need options to be set up for this to make sense
this.setValue( config.value );
};
/* Setup */
OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.static.supportsSimpleLabel = false;
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
.toArray().map( function ( el ) { return el.value; } );
return state;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
// Cannot reuse the `<input type=checkbox>` set
delete config.$input;
return config;
};
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
// Actually unused
return $( '<div>' );
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
.toArray().map( function ( el ) { return el.value; } );
if ( this.value !== value ) {
this.setValue( value );
}
return this.value;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
value = this.cleanUpValue( value );
this.checkboxMultiselectWidget.selectItemsByData( value );
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
return this;
};
/**
* Clean up incoming value.
*
* @param {string[]} value Original value
* @return {string[]} Cleaned up value
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
var i, singleValue,
cleanValue = [];
if ( !Array.isArray( value ) ) {
return cleanValue;
}
for ( i = 0; i < value.length; i++ ) {
singleValue =
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
// Remove options that we don't have here
if ( !this.checkboxMultiselectWidget.getItemFromData( singleValue ) ) {
continue;
}
cleanValue.push( singleValue );
}
return cleanValue;
};
/**
* @inheritdoc
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
this.checkboxMultiselectWidget.setDisabled( state );
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
* @chainable
*/
OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
var widget = this;
// Rebuild the checkboxMultiselectWidget menu
this.checkboxMultiselectWidget
.clearItems()
.addItems( options.map( function ( opt ) {
var optValue, item, optDisabled;
optValue =
OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
optDisabled = opt.disabled !== undefined ? opt.disabled : false;
item = new OO.ui.CheckboxMultioptionWidget( {
data: optValue,
label: opt.label !== undefined ? opt.label : optValue,
disabled: optDisabled
} );
// Set the 'name' and 'value' for form submission
item.checkbox.$input.attr( 'name', widget.inputName );
item.checkbox.setValue( optValue );
return item;
} ) );
// Re-set the value, checking the checkboxes as needed.
// This will also get rid of any stale options that we just removed.
this.setValue( this.getValue() );
return this;
};
/**
* TextInputWidgets, like HTML text inputs, can be configured with options that customize the
* size of the field as well as its presentation. In addition, these widgets can be configured
* with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
* validation-pattern (used to determine if an input value is valid or not) and an input filter,
* which modifies incoming values rather than validating them.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* @example
* // Example of a text input widget
* var textInput = new OO.ui.TextInputWidget( {
* value: 'Text input'
* } )
* $( 'body' ).append( textInput.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @class
* @extends OO.ui.InputWidget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.PendingElement
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
* 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true.
*
* Some values of `type` result in additional behaviors:
*
* - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
* empties the text field
* @cfg {string} [placeholder] Placeholder text
* @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
* instruct the browser to focus this widget.
* @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
* @cfg {number} [maxLength] Maximum number of characters allowed in the input.
* @cfg {boolean} [multiline=false] Allow multiple lines of text
* @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
* specifies minimum number of rows to display.
* @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
* Use the #maxRows config to specify a maximum number of displayed rows.
* @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
* Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
* @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
* the value or placeholder text: `'before'` or `'after'`
* @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
* @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
* @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
* pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
* (the value must contain only numbers); when RegExp, a regular expression that must match the
* value for it to be considered valid; when Function, a function receiving the value as parameter
* that must return true, or promise resolving to true, for it to be considered valid.
*/
OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
// Configuration initialization
config = $.extend( {
type: 'text',
labelPosition: 'after'
}, config );
if ( config.type === 'search' ) {
OO.ui.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
if ( config.icon === undefined ) {
config.icon = 'search';
}
// indicator: 'clear' is set dynamically later, depending on value
}
// Parent constructor
OO.ui.TextInputWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
OO.ui.mixin.LabelElement.call( this, config );
// Properties
this.type = this.getSaneType( config );
this.readOnly = false;
this.required = false;
this.multiline = !!config.multiline;
this.autosize = !!config.autosize;
this.minRows = config.rows !== undefined ? config.rows : '';
this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
this.validate = null;
this.styleHeight = null;
this.scrollWidth = null;
// Clone for resizing
if ( this.autosize ) {
this.$clone = this.$input
.clone()
.insertAfter( this.$input )
.attr( 'aria-hidden', 'true' )
.addClass( 'oo-ui-element-hidden' );
}
this.setValidation( config.validate );
this.setLabelPosition( config.labelPosition );
// Events
this.$input.on( {
keypress: this.onKeyPress.bind( this ),
blur: this.onBlur.bind( this ),
focus: this.onFocus.bind( this )
} );
this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
this.on( 'labelChange', this.updatePosition.bind( this ) );
this.connect( this, {
change: 'onChange',
disable: 'onDisable'
} );
this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
// Initialization
this.$element
.addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
.append( this.$icon, this.$indicator );
this.setReadOnly( !!config.readOnly );
this.setRequired( !!config.required );
this.updateSearchIndicator();
if ( config.placeholder !== undefined ) {
this.$input.attr( 'placeholder', config.placeholder );
}
if ( config.maxLength !== undefined ) {
this.$input.attr( 'maxlength', config.maxLength );
}
if ( config.autofocus ) {
this.$input.attr( 'autofocus', 'autofocus' );
}
if ( config.autocomplete === false ) {
this.$input.attr( 'autocomplete', 'off' );
// Turning off autocompletion also disables "form caching" when the user navigates to a
// different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
$( window ).on( {
beforeunload: function () {
this.$input.removeAttr( 'autocomplete' );
}.bind( this ),
pageshow: function () {
// Browsers don't seem to actually fire this event on "Back", they instead just reload the
// whole page... it shouldn't hurt, though.
this.$input.attr( 'autocomplete', 'off' );
}.bind( this )
} );
}
if ( this.multiline && config.rows ) {
this.$input.attr( 'rows', config.rows );
}
if ( this.label || config.autosize ) {
this.isWaitingToBeAttached = true;
this.installParentChangeDetector();
}
};
/* Setup */
OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
/* Static Properties */
OO.ui.TextInputWidget.static.validationPatterns = {
'non-empty': /.+/,
integer: /^\d+$/
};
/* Static Methods */
/**
* @inheritdoc
*/
OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
if ( config.multiline ) {
state.scrollTop = config.$input.scrollTop();
}
return state;
};
/* Events */
/**
* An `enter` event is emitted when the user presses 'enter' inside the text box.
*
* Not emitted if the input is multiline.
*
* @event enter
*/
/**
* A `resize` event is emitted when autosize is set and the widget resizes
*
* @event resize
*/
/* Methods */
/**
* Handle icon mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
this.$input[ 0 ].focus();
return false;
}
};
/**
* Handle indicator mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
if ( this.type === 'search' ) {
// Clear the text field
this.setValue( '' );
}
this.$input[ 0 ].focus();
return false;
}
};
/**
* Handle key press events.
*
* @private
* @param {jQuery.Event} e Key press event
* @fires enter If enter key is pressed and input is not multiline
*/
OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
this.emit( 'enter', e );
}
};
/**
* Handle blur events.
*
* @private
* @param {jQuery.Event} e Blur event
*/
OO.ui.TextInputWidget.prototype.onBlur = function () {
this.setValidityFlag();
};
/**
* Handle focus events.
*
* @private
* @param {jQuery.Event} e Focus event
*/
OO.ui.TextInputWidget.prototype.onFocus = function () {
if ( this.isWaitingToBeAttached ) {
// If we've received focus, then we must be attached to the document, and if
// isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
this.onElementAttach();
}
this.setValidityFlag( true );
};
/**
* Handle element attach events.
*
* @private
* @param {jQuery.Event} e Element attach event
*/
OO.ui.TextInputWidget.prototype.onElementAttach = function () {
this.isWaitingToBeAttached = false;
// Any previously calculated size is now probably invalid if we reattached elsewhere
this.valCache = null;
this.adjustSize();
this.positionLabel();
};
/**
* Handle change events.
*
* @param {string} value
* @private
*/
OO.ui.TextInputWidget.prototype.onChange = function () {
this.updateSearchIndicator();
this.adjustSize();
};
/**
* Handle debounced change events.
*
* @param {string} value
* @private
*/
OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
this.setValidityFlag();
};
/**
* Handle disable events.
*
* @param {boolean} disabled Element is disabled
* @private
*/
OO.ui.TextInputWidget.prototype.onDisable = function () {
this.updateSearchIndicator();
};
/**
* Check if the input is {@link #readOnly read-only}.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isReadOnly = function () {
return this.readOnly;
};
/**
* Set the {@link #readOnly read-only} state of the input.
*
* @param {boolean} state Make input read-only
* @chainable
*/
OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
this.readOnly = !!state;
this.$input.prop( 'readOnly', this.readOnly );
this.updateSearchIndicator();
return this;
};
/**
* Check if the input is {@link #required required}.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isRequired = function () {
return this.required;
};
/**
* Set the {@link #required required} state of the input.
*
* @param {boolean} state Make input required
* @chainable
*/
OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
this.required = !!state;
if ( this.required ) {
this.$input
.attr( 'required', 'required' )
.attr( 'aria-required', 'true' );
if ( this.getIndicator() === null ) {
this.setIndicator( 'required' );
}
} else {
this.$input
.removeAttr( 'required' )
.removeAttr( 'aria-required' );
if ( this.getIndicator() === 'required' ) {
this.setIndicator( null );
}
}
this.updateSearchIndicator();
return this;
};
/**
* Support function for making #onElementAttach work across browsers.
*
* This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
* event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
*
* Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
* first time that the element gets attached to the documented.
*/
OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
var mutationObserver, onRemove, topmostNode, fakeParentNode,
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
widget = this;
if ( MutationObserver ) {
// The new way. If only it wasn't so ugly.
if ( this.isElementAttached() ) {
// Widget is attached already, do nothing. This breaks the functionality of this function when
// the widget is detached and reattached. Alas, doing this correctly with MutationObserver
// would require observation of the whole document, which would hurt performance of other,
// more important code.
return;
}
// Find topmost node in the tree
topmostNode = this.$element[ 0 ];
while ( topmostNode.parentNode ) {
topmostNode = topmostNode.parentNode;
}
// We have no way to detect the $element being attached somewhere without observing the entire
// DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
// parent node of $element, and instead detect when $element is removed from it (and thus
// probably attached somewhere else). If there is no parent, we create a "fake" one. If it
// doesn't get attached, we end up back here and create the parent.
mutationObserver = new MutationObserver( function ( mutations ) {
var i, j, removedNodes;
for ( i = 0; i < mutations.length; i++ ) {
removedNodes = mutations[ i ].removedNodes;
for ( j = 0; j < removedNodes.length; j++ ) {
if ( removedNodes[ j ] === topmostNode ) {
setTimeout( onRemove, 0 );
return;
}
}
}
} );
onRemove = function () {
// If the node was attached somewhere else, report it
if ( widget.isElementAttached() ) {
widget.onElementAttach();
}
mutationObserver.disconnect();
widget.installParentChangeDetector();
};
// Create a fake parent and observe it
fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
mutationObserver.observe( fakeParentNode, { childList: true } );
} else {
// Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
// detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
}
};
/**
* Automatically adjust the size of the text input.
*
* This only affects #multiline inputs that are {@link #autosize autosized}.
*
* @chainable
* @fires resize
*/
OO.ui.TextInputWidget.prototype.adjustSize = function () {
var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
idealHeight, newHeight, scrollWidth, property;
if ( this.isWaitingToBeAttached ) {
// #onElementAttach will be called soon, which calls this method
return this;
}
if ( this.multiline && this.$input.val() !== this.valCache ) {
if ( this.autosize ) {
this.$clone
.val( this.$input.val() )
.attr( 'rows', this.minRows )
// Set inline height property to 0 to measure scroll height
.css( 'height', 0 );
this.$clone.removeClass( 'oo-ui-element-hidden' );
this.valCache = this.$input.val();
scrollHeight = this.$clone[ 0 ].scrollHeight;
// Remove inline height property to measure natural heights
this.$clone.css( 'height', '' );
innerHeight = this.$clone.innerHeight();
outerHeight = this.$clone.outerHeight();
// Measure max rows height
this.$clone
.attr( 'rows', this.maxRows )
.css( 'height', 'auto' )
.val( '' );
maxInnerHeight = this.$clone.innerHeight();
// Difference between reported innerHeight and scrollHeight with no scrollbars present.
// This is sometimes non-zero on Blink-based browsers, depending on zoom level.
measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
this.$clone.addClass( 'oo-ui-element-hidden' );
// Only apply inline height when expansion beyond natural height is needed
// Use the difference between the inner and outer height as a buffer
newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
if ( newHeight !== this.styleHeight ) {
this.$input.css( 'height', newHeight );
this.styleHeight = newHeight;
this.emit( 'resize' );
}
}
scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
if ( scrollWidth !== this.scrollWidth ) {
property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
// Reset
this.$label.css( { right: '', left: '' } );
this.$indicator.css( { right: '', left: '' } );
if ( scrollWidth ) {
this.$indicator.css( property, scrollWidth );
if ( this.labelPosition === 'after' ) {
this.$label.css( property, scrollWidth );
}
}
this.scrollWidth = scrollWidth;
this.positionLabel();
}
}
return this;
};
/**
* @inheritdoc
* @protected
*/
OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
if ( config.multiline ) {
return $( '<textarea>' );
} else if ( this.getSaneType( config ) === 'number' ) {
return $( '<input>' )
.attr( 'step', 'any' )
.attr( 'type', 'number' );
} else {
return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
}
};
/**
* Get sanitized value for 'type' for given config.
*
* @param {Object} config Configuration options
* @return {string|null}
* @private
*/
OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
var allowedTypes = [
'text',
'password',
'search',
'email',
'url',
'date',
'month',
'number'
];
return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
};
/**
* Check if the input supports multiple lines.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isMultiline = function () {
return !!this.multiline;
};
/**
* Check if the input automatically adjusts its size.
*
* @return {boolean}
*/
OO.ui.TextInputWidget.prototype.isAutosizing = function () {
return !!this.autosize;
};
/**
* Focus the input and select a specified range within the text.
*
* @param {number} from Select from offset
* @param {number} [to] Select to offset, defaults to from
* @chainable
*/
OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
var isBackwards, start, end,
input = this.$input[ 0 ];
to = to || from;
isBackwards = to < from;
start = isBackwards ? to : from;
end = isBackwards ? from : to;
this.focus();
try {
input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
} catch ( e ) {
// IE throws an exception if you call setSelectionRange on a unattached DOM node.
// Rather than expensively check if the input is attached every time, just check
// if it was the cause of an error being thrown. If not, rethrow the error.
if ( this.getElementDocument().body.contains( input ) ) {
throw e;
}
}
return this;
};
/**
* Get an object describing the current selection range in a directional manner
*
* @return {Object} Object containing 'from' and 'to' offsets
*/
OO.ui.TextInputWidget.prototype.getRange = function () {
var input = this.$input[ 0 ],
start = input.selectionStart,
end = input.selectionEnd,
isBackwards = input.selectionDirection === 'backward';
return {
from: isBackwards ? end : start,
to: isBackwards ? start : end
};
};
/**
* Get the length of the text input value.
*
* This could differ from the length of #getValue if the
* value gets filtered
*
* @return {number} Input length
*/
OO.ui.TextInputWidget.prototype.getInputLength = function () {
return this.$input[ 0 ].value.length;
};
/**
* Focus the input and select the entire text.
*
* @chainable
*/
OO.ui.TextInputWidget.prototype.select = function () {
return this.selectRange( 0, this.getInputLength() );
};
/**
* Focus the input and move the cursor to the start.
*
* @chainable
*/
OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
return this.selectRange( 0 );
};
/**
* Focus the input and move the cursor to the end.
*
* @chainable
*/
OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
return this.selectRange( this.getInputLength() );
};
/**
* Insert new content into the input.
*
* @param {string} content Content to be inserted
* @chainable
*/
OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
var start, end,
range = this.getRange(),
value = this.getValue();
start = Math.min( range.from, range.to );
end = Math.max( range.from, range.to );
this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
this.selectRange( start + content.length );
return this;
};
/**
* Insert new content either side of a selection.
*
* @param {string} pre Content to be inserted before the selection
* @param {string} post Content to be inserted after the selection
* @chainable
*/
OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
var start, end,
range = this.getRange(),
offset = pre.length;
start = Math.min( range.from, range.to );
end = Math.max( range.from, range.to );
this.selectRange( start ).insertContent( pre );
this.selectRange( offset + end ).insertContent( post );
this.selectRange( offset + start, offset + end );
return this;
};
/**
* Set the validation pattern.
*
* The validation pattern is either a regular expression, a function, or the symbolic name of a
* pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
* value must contain only numbers).
*
* @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
* of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
*/
OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
if ( validate instanceof RegExp || validate instanceof Function ) {
this.validate = validate;
} else {
this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
}
};
/**
* Sets the 'invalid' flag appropriately.
*
* @param {boolean} [isValid] Optionally override validation result
*/
OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
var widget = this,
setFlag = function ( valid ) {
if ( !valid ) {
widget.$input.attr( 'aria-invalid', 'true' );
} else {
widget.$input.removeAttr( 'aria-invalid' );
}
widget.setFlags( { invalid: !valid } );
};
if ( isValid !== undefined ) {
setFlag( isValid );
} else {
this.getValidity().then( function () {
setFlag( true );
}, function () {
setFlag( false );
} );
}
};
/**
* Get the validity of current value.
*
* This method returns a promise that resolves if the value is valid and rejects if
* it isn't. Uses the {@link #validate validation pattern} to check for validity.
*
* @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
*/
OO.ui.TextInputWidget.prototype.getValidity = function () {
var result;
function rejectOrResolve( valid ) {
if ( valid ) {
return $.Deferred().resolve().promise();
} else {
return $.Deferred().reject().promise();
}
}
// Check browser validity and reject if it is invalid
if (
this.$input[ 0 ].checkValidity !== undefined &&
this.$input[ 0 ].checkValidity() === false
) {
return rejectOrResolve( false );
}
// Run our checks if the browser thinks the field is valid
if ( this.validate instanceof Function ) {
result = this.validate( this.getValue() );
if ( result && $.isFunction( result.promise ) ) {
return result.promise().then( function ( valid ) {
return rejectOrResolve( valid );
} );
} else {
return rejectOrResolve( result );
}
} else {
return rejectOrResolve( this.getValue().match( this.validate ) );
}
};
/**
* Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
*
* @param {string} labelPosition Label position, 'before' or 'after'
* @chainable
*/
OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
this.labelPosition = labelPosition;
if ( this.label ) {
// If there is no label and we only change the position, #updatePosition is a no-op,
// but it takes really a lot of work to do nothing.
this.updatePosition();
}
return this;
};
/**
* Update the position of the inline label.
*
* This method is called by #setLabelPosition, and can also be called on its own if
* something causes the label to be mispositioned.
*
* @chainable
*/
OO.ui.TextInputWidget.prototype.updatePosition = function () {
var after = this.labelPosition === 'after';
this.$element
.toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
.toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
this.valCache = null;
this.scrollWidth = null;
this.adjustSize();
this.positionLabel();
return this;
};
/**
* Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
* already empty or when it's not editable.
*/
OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
if ( this.type === 'search' ) {
if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
this.setIndicator( null );
} else {
this.setIndicator( 'clear' );
}
}
};
/**
* Position the label by setting the correct padding on the input.
*
* @private
* @chainable
*/
OO.ui.TextInputWidget.prototype.positionLabel = function () {
var after, rtl, property;
if ( this.isWaitingToBeAttached ) {
// #onElementAttach will be called soon, which calls this method
return this;
}
// Clear old values
this.$input
// Clear old values if present
.css( {
'padding-right': '',
'padding-left': ''
} );
if ( this.label ) {
this.$element.append( this.$label );
} else {
this.$label.detach();
return;
}
after = this.labelPosition === 'after';
rtl = this.$element.css( 'direction' ) === 'rtl';
property = after === rtl ? 'padding-left' : 'padding-right';
this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
return this;
};
/**
* @inheritdoc
*/
OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
if ( state.scrollTop !== undefined ) {
this.$input.scrollTop( state.scrollTop );
}
};
/**
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
config = $.extend( {
icon: 'search'
}, config );
// Set type to text so that TextInputWidget doesn't
// get stuck in an infinite loop.
config.type = 'text';
// Parent constructor
OO.ui.SearchInputWidget.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-textInputWidget-type-search' );
this.updateSearchIndicator();
this.connect( this, {
disable: 'onDisable'
} );
};
/* Setup */
OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
/* Methods */
/**
* @inheritdoc
* @protected
*/
OO.ui.SearchInputWidget.prototype.getInputElement = function () {
return $( '<input>' ).attr( 'type', 'search' );
};
/**
* @inheritdoc
*/
OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
// Clear the text field
this.setValue( '' );
this.$input[ 0 ].focus();
return false;
}
};
/**
* Update the 'clear' indicator displayed on type: 'search' text
* fields, hiding it when the field is already empty or when it's not
* editable.
*/
OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
this.setIndicator( null );
} else {
this.setIndicator( 'clear' );
}
};
/**
* @inheritdoc
*/
OO.ui.SearchInputWidget.prototype.onChange = function () {
OO.ui.SearchInputWidget.parent.prototype.onChange.call( this );
this.updateSearchIndicator();
};
/**
* Handle disable events.
*
* @param {boolean} disabled Element is disabled
* @private
*/
OO.ui.SearchInputWidget.prototype.onDisable = function () {
this.updateSearchIndicator();
};
/**
* @inheritdoc
*/
OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
this.updateSearchIndicator();
return this;
};
/**
* ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
* can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
* a value can be chosen instead). Users can choose options from the combo box in one of two ways:
*
* - by typing a value in the text input field. If the value exactly matches the value of a menu
* option, that option will appear to be selected.
* - by choosing a value from the menu. The value of the chosen option will then appear in the text
* input field.
*
* This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
*
* For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example: A ComboBoxInputWidget.
* var comboBox = new OO.ui.ComboBoxInputWidget( {
* label: 'ComboBoxInputWidget',
* value: 'Option 1',
* menu: {
* items: [
* new OO.ui.MenuOptionWidget( {
* data: 'Option 1',
* label: 'Option One'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 2',
* label: 'Option Two'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 3',
* label: 'Option Three'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 4',
* label: 'Option Four'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 5',
* label: 'Option Five'
* } )
* ]
* }
* } );
* $( 'body' ).append( comboBox.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.TextInputWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
* @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
* @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
* the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
* containing `<div>` and has a larger area. By default, the menu uses relative positioning.
*/
OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
// Configuration initialization
config = $.extend( {
autocomplete: false
}, config );
// ComboBoxInputWidget shouldn't support multiline
config.multiline = false;
// Parent constructor
OO.ui.ComboBoxInputWidget.parent.call( this, config );
// Properties
this.$overlay = config.$overlay || this.$element;
this.dropdownButton = new OO.ui.ButtonWidget( {
classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
indicator: 'down',
disabled: this.disabled
} );
this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
{
widget: this,
input: this,
$container: this.$element,
disabled: this.isDisabled()
},
config.menu
) );
// Events
this.connect( this, {
change: 'onInputChange',
enter: 'onInputEnter'
} );
this.dropdownButton.connect( this, {
click: 'onDropdownButtonClick'
} );
this.menu.connect( this, {
choose: 'onMenuChoose',
add: 'onMenuItemsChange',
remove: 'onMenuItemsChange'
} );
// Initialization
this.$input.attr( {
role: 'combobox',
'aria-autocomplete': 'list'
} );
// Do not override options set via config.menu.items
if ( config.options !== undefined ) {
this.setOptions( config.options );
}
this.$field = $( '<div>' )
.addClass( 'oo-ui-comboBoxInputWidget-field' )
.append( this.$input, this.dropdownButton.$element );
this.$element
.addClass( 'oo-ui-comboBoxInputWidget' )
.append( this.$field );
this.$overlay.append( this.menu.$element );
this.onMenuItemsChange();
};
/* Setup */
OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
/* Methods */
/**
* Get the combobox's menu.
*
* @return {OO.ui.FloatingMenuSelectWidget} Menu widget
*/
OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
return this.menu;
};
/**
* Get the combobox's text input widget.
*
* @return {OO.ui.TextInputWidget} Text input widget
*/
OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
return this;
};
/**
* Handle input change events.
*
* @private
* @param {string} value New value
*/
OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
var match = this.menu.getItemFromData( value );
this.menu.selectItem( match );
if ( this.menu.getHighlightedItem() ) {
this.menu.highlightItem( match );
}
if ( !this.isDisabled() ) {
this.menu.toggle( true );
}
};
/**
* Handle input enter events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
if ( !this.isDisabled() ) {
this.menu.toggle( false );
}
};
/**
* Handle button click events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
this.menu.toggle();
this.$input[ 0 ].focus();
};
/**
* Handle menu choose events.
*
* @private
* @param {OO.ui.OptionWidget} item Chosen item
*/
OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
this.setValue( item.getData() );
};
/**
* Handle menu item change events.
*
* @private
*/
OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
var match = this.menu.getItemFromData( this.getValue() );
this.menu.selectItem( match );
if ( this.menu.getHighlightedItem() ) {
this.menu.highlightItem( match );
}
this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
};
/**
* @inheritdoc
*/
OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
// Parent method
OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.dropdownButton ) {
this.dropdownButton.setDisabled( this.isDisabled() );
}
if ( this.menu ) {
this.menu.setDisabled( this.isDisabled() );
}
return this;
};
/**
* Set the options available for this input.
*
* @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
* @chainable
*/
OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
this.getMenu()
.clearItems()
.addItems( options.map( function ( opt ) {
return new OO.ui.MenuOptionWidget( {
data: opt.data,
label: opt.label !== undefined ? opt.label : opt.data
} );
} ) );
return this;
};
/**
* FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
* which is a widget that is specified by reference before any optional configuration settings.
*
* Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
*
* - **left**: The label is placed before the field-widget and aligned with the left margin.
* A left-alignment is used for forms with many fields.
* - **right**: The label is placed before the field-widget and aligned to the right margin.
* A right-alignment is used for long but familiar forms which users tab through,
* verifying the current field with a quick glance at the label.
* - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
* that users fill out from top to bottom.
* - **inline**: The label is placed after the field-widget and aligned to the left.
* An inline-alignment is best used with checkboxes or radio buttons.
*
* Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
* Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {OO.ui.Widget} fieldWidget Field widget
* @param {Object} [config] Configuration options
* @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
* @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
* in the upper-right corner of the rendered field; clicking it will display the text in a popup.
* For important messages, you are advised to use `notices`, as they are always shown.
*
* @throws {Error} An error is thrown if no widget is specified
*/
OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
config = fieldWidget;
fieldWidget = config.fieldWidget;
}
// Make sure we have required constructor arguments
if ( fieldWidget === undefined ) {
throw new Error( 'Widget not found' );
}
// Configuration initialization
config = $.extend( { align: 'left' }, config );
// Parent constructor
OO.ui.FieldLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
$label: $( '<label>' )
} ) );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
// Properties
this.fieldWidget = fieldWidget;
this.errors = [];
this.notices = [];
this.$field = $( '<div>' );
this.$messages = $( '<ul>' );
this.$header = $( '<div>' );
this.$body = $( '<div>' );
this.align = null;
if ( config.help ) {
this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
popup: {
padded: true
},
classes: [ 'oo-ui-fieldLayout-help' ],
framed: false,
icon: 'info'
} );
if ( config.help instanceof OO.ui.HtmlSnippet ) {
this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
} else {
this.popupButtonWidget.getPopup().$body.text( config.help );
}
this.$help = this.popupButtonWidget.$element;
} else {
this.$help = $( [] );
}
// Events
this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
// Initialization
if ( fieldWidget.constructor.static.supportsSimpleLabel ) {
if ( this.fieldWidget.getInputId() ) {
this.$label.attr( 'for', this.fieldWidget.getInputId() );
}
}
this.$element
.addClass( 'oo-ui-fieldLayout' )
.toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
.append( this.$body );
this.$body.addClass( 'oo-ui-fieldLayout-body' );
this.$header.addClass( 'oo-ui-fieldLayout-header' );
this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
this.$field
.addClass( 'oo-ui-fieldLayout-field' )
.append( this.fieldWidget.$element );
this.setErrors( config.errors || [] );
this.setNotices( config.notices || [] );
this.setAlignment( config.align );
};
/* Setup */
OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
/* Methods */
/**
* Handle field disable events.
*
* @private
* @param {boolean} value Field is disabled
*/
OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
};
/**
* Get the widget contained by the field.
*
* @return {OO.ui.Widget} Field widget
*/
OO.ui.FieldLayout.prototype.getField = function () {
return this.fieldWidget;
};
/**
* @protected
* @param {string} kind 'error' or 'notice'
* @param {string|OO.ui.HtmlSnippet} text
* @return {jQuery}
*/
OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
var $listItem, $icon, message;
$listItem = $( '<li>' );
if ( kind === 'error' ) {
$icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
} else if ( kind === 'notice' ) {
$icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
} else {
$icon = '';
}
message = new OO.ui.LabelWidget( { label: text } );
$listItem
.append( $icon, message.$element )
.addClass( 'oo-ui-fieldLayout-messages-' + kind );
return $listItem;
};
/**
* Set the field alignment mode.
*
* @private
* @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
* @chainable
*/
OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
if ( value !== this.align ) {
// Default to 'left'
if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
value = 'left';
}
// Reorder elements
if ( value === 'top' ) {
this.$header.append( this.$label, this.$help );
this.$body.append( this.$header, this.$field );
} else if ( value === 'inline' ) {
this.$header.append( this.$label, this.$help );
this.$body.append( this.$field, this.$header );
} else {
this.$header.append( this.$label );
this.$body.append( this.$header, this.$help, this.$field );
}
// Set classes. The following classes can be used here:
// * oo-ui-fieldLayout-align-left
// * oo-ui-fieldLayout-align-right
// * oo-ui-fieldLayout-align-top
// * oo-ui-fieldLayout-align-inline
if ( this.align ) {
this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
}
this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
this.align = value;
}
return this;
};
/**
* Set the list of error messages.
*
* @param {Array} errors Error messages about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @chainable
*/
OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
this.errors = errors.slice();
this.updateMessages();
return this;
};
/**
* Set the list of notice messages.
*
* @param {Array} notices Notices about the widget, which will be displayed below the widget.
* The array may contain strings or OO.ui.HtmlSnippet instances.
* @chainable
*/
OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
this.notices = notices.slice();
this.updateMessages();
return this;
};
/**
* Update the rendering of error and notice messages.
*
* @private
*/
OO.ui.FieldLayout.prototype.updateMessages = function () {
var i;
this.$messages.empty();
if ( this.errors.length || this.notices.length ) {
this.$body.after( this.$messages );
} else {
this.$messages.remove();
return;
}
for ( i = 0; i < this.notices.length; i++ ) {
this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
}
for ( i = 0; i < this.errors.length; i++ ) {
this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
}
};
/**
* ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
* and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
* is required and is specified before any optional configuration settings.
*
* Labels can be aligned in one of four ways:
*
* - **left**: The label is placed before the field-widget and aligned with the left margin.
* A left-alignment is used for forms with many fields.
* - **right**: The label is placed before the field-widget and aligned to the right margin.
* A right-alignment is used for long but familiar forms which users tab through,
* verifying the current field with a quick glance at the label.
* - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
* that users fill out from top to bottom.
* - **inline**: The label is placed after the field-widget and aligned to the left.
* An inline-alignment is best used with checkboxes or radio buttons.
*
* Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
* text is specified.
*
* @example
* // Example of an ActionFieldLayout
* var actionFieldLayout = new OO.ui.ActionFieldLayout(
* new OO.ui.TextInputWidget( {
* placeholder: 'Field widget'
* } ),
* new OO.ui.ButtonWidget( {
* label: 'Button'
* } ),
* {
* label: 'An ActionFieldLayout. This label is aligned top',
* align: 'top',
* help: 'This is help text'
* }
* );
*
* $( 'body' ).append( actionFieldLayout.$element );
*
* @class
* @extends OO.ui.FieldLayout
*
* @constructor
* @param {OO.ui.Widget} fieldWidget Field widget
* @param {OO.ui.ButtonWidget} buttonWidget Button widget
* @param {Object} config
*/
OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
config = fieldWidget;
fieldWidget = config.fieldWidget;
buttonWidget = config.buttonWidget;
}
// Parent constructor
OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
// Properties
this.buttonWidget = buttonWidget;
this.$button = $( '<div>' );
this.$input = $( '<div>' );
// Initialization
this.$element
.addClass( 'oo-ui-actionFieldLayout' );
this.$button
.addClass( 'oo-ui-actionFieldLayout-button' )
.append( this.buttonWidget.$element );
this.$input
.addClass( 'oo-ui-actionFieldLayout-input' )
.append( this.fieldWidget.$element );
this.$field
.append( this.$input, this.$button );
};
/* Setup */
OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
/**
* FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
* which each contain an individual widget and, optionally, a label. Each Fieldset can be
* configured with a label as well. For more information and examples,
* please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example of a fieldset layout
* var input1 = new OO.ui.TextInputWidget( {
* placeholder: 'A text input field'
* } );
*
* var input2 = new OO.ui.TextInputWidget( {
* placeholder: 'A text input field'
* } );
*
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Example of a fieldset layout'
* } );
*
* fieldset.addItems( [
* new OO.ui.FieldLayout( input1, {
* label: 'Field One'
* } ),
* new OO.ui.FieldLayout( input2, {
* label: 'Field Two'
* } )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
* @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
* in the upper-right corner of the rendered field; clicking it will display the text in a popup.
* For important messages, you are advised to use `notices`, as they are always shown.
*/
OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.FieldsetLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: $( '<div>' ) } ) );
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.$header = $( '<div>' );
if ( config.help ) {
this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
popup: {
padded: true
},
classes: [ 'oo-ui-fieldsetLayout-help' ],
framed: false,
icon: 'info'
} );
if ( config.help instanceof OO.ui.HtmlSnippet ) {
this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
} else {
this.popupButtonWidget.getPopup().$body.text( config.help );
}
this.$help = this.popupButtonWidget.$element;
} else {
this.$help = $( [] );
}
// Initialization
this.$header
.addClass( 'oo-ui-fieldsetLayout-header' )
.append( this.$icon, this.$label, this.$help );
this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
this.$element
.addClass( 'oo-ui-fieldsetLayout' )
.prepend( this.$header, this.$group );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.FieldsetLayout.static.tagName = 'fieldset';
/**
* FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
* form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
* HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
* See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
*
* Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
* includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
* OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
* some fancier controls. Some controls have both regular and InputWidget variants, for example
* OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
* often have simplified APIs to match the capabilities of HTML forms.
* See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
*
* @example
* // Example of a form layout that wraps a fieldset layout
* var input1 = new OO.ui.TextInputWidget( {
* placeholder: 'Username'
* } );
* var input2 = new OO.ui.TextInputWidget( {
* placeholder: 'Password',
* type: 'password'
* } );
* var submit = new OO.ui.ButtonInputWidget( {
* label: 'Submit'
* } );
*
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'A form layout'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( input1, {
* label: 'Username',
* align: 'top'
* } ),
* new OO.ui.FieldLayout( input2, {
* label: 'Password',
* align: 'top'
* } ),
* new OO.ui.FieldLayout( submit )
* ] );
* var form = new OO.ui.FormLayout( {
* items: [ fieldset ],
* action: '/api/formhandler',
* method: 'get'
* } )
* $( 'body' ).append( form.$element );
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [method] HTML form `method` attribute
* @cfg {string} [action] HTML form `action` attribute
* @cfg {string} [enctype] HTML form `enctype` attribute
* @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
*/
OO.ui.FormLayout = function OoUiFormLayout( config ) {
var action;
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.FormLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Events
this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
// Make sure the action is safe
action = config.action;
if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
action = './' + action;
}
// Initialization
this.$element
.addClass( 'oo-ui-formLayout' )
.attr( {
method: config.method,
action: action,
enctype: config.enctype
} );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
/* Events */
/**
* A 'submit' event is emitted when the form is submitted.
*
* @event submit
*/
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.FormLayout.static.tagName = 'form';
/* Methods */
/**
* Handle form submit events.
*
* @private
* @param {jQuery.Event} e Submit event
* @fires submit
*/
OO.ui.FormLayout.prototype.onFormSubmit = function () {
if ( this.emit( 'submit' ) ) {
return false;
}
};
/**
* PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
* and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
*
* @example
* // Example of a panel layout
* var panel = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true,
* padded: true,
* $content: $( '<p>A panel layout with padding and a frame.</p>' )
* } );
* $( 'body' ).append( panel.$element );
*
* @class
* @extends OO.ui.Layout
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [scrollable=false] Allow vertical scrolling
* @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
* @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
* @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
*/
OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
// Configuration initialization
config = $.extend( {
scrollable: false,
padded: false,
expanded: true,
framed: false
}, config );
// Parent constructor
OO.ui.PanelLayout.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-panelLayout' );
if ( config.scrollable ) {
this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
}
if ( config.padded ) {
this.$element.addClass( 'oo-ui-panelLayout-padded' );
}
if ( config.expanded ) {
this.$element.addClass( 'oo-ui-panelLayout-expanded' );
}
if ( config.framed ) {
this.$element.addClass( 'oo-ui-panelLayout-framed' );
}
};
/* Setup */
OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
/* Methods */
/**
* Focus the panel layout
*
* The default implementation just focuses the first focusable element in the panel
*/
OO.ui.PanelLayout.prototype.focus = function () {
OO.ui.findFocusable( this.$element ).focus();
};
/**
* HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
* items), with small margins between them. Convenient when you need to put a number of block-level
* widgets on a single line next to each other.
*
* Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
*
* @example
* // HorizontalLayout with a text input and a label
* var layout = new OO.ui.HorizontalLayout( {
* items: [
* new OO.ui.LabelWidget( { label: 'Label' } ),
* new OO.ui.TextInputWidget( { value: 'Text' } )
* ]
* } );
* $( 'body' ).append( layout.$element );
*
* @class
* @extends OO.ui.Layout
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
*/
OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.HorizontalLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-horizontalLayout' );
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
}( OO ) );
/*!
* OOjs UI v0.19.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-02-14T22:47:20Z
*/
( function ( OO ) {
'use strict';
/**
* DraggableElement is a mixin class used to create elements that can be clicked
* and dragged by a mouse to a new position within a group. This class must be used
* in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
* the draggable elements.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$handle] The part of the element which can be used for dragging, defaults to the whole element
*/
OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement( config ) {
config = config || {};
// Properties
this.index = null;
this.$handle = config.$handle || this.$element;
this.wasHandleUsed = null;
// Initialize and events
this.$element.addClass( 'oo-ui-draggableElement' )
// We make the entire element draggable, not just the handle, so that
// the whole element appears to move. wasHandleUsed prevents drags from
// starting outside the handle
.attr( 'draggable', true )
.on( {
mousedown: this.onDragMouseDown.bind( this ),
dragstart: this.onDragStart.bind( this ),
dragover: this.onDragOver.bind( this ),
dragend: this.onDragEnd.bind( this ),
drop: this.onDrop.bind( this )
} );
this.$handle.addClass( 'oo-ui-draggableElement-handle' );
};
OO.initClass( OO.ui.mixin.DraggableElement );
/* Events */
/**
* @event dragstart
*
* A dragstart event is emitted when the user clicks and begins dragging an item.
* @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
*/
/**
* @event dragend
* A dragend event is emitted when the user drags an item and releases the mouse,
* thus terminating the drag operation.
*/
/**
* @event drop
* A drop event is emitted when the user drags an item and then releases the mouse button
* over a valid target.
*/
/* Static Properties */
/**
* @inheritdoc OO.ui.mixin.ButtonElement
*/
OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
/* Methods */
/**
* Respond to mousedown event.
*
* @private
* @param {jQuery.Event} e Drag event
*/
OO.ui.mixin.DraggableElement.prototype.onDragMouseDown = function ( e ) {
this.wasHandleUsed =
// Optimization: if the handle is the whole element this is always true
this.$handle[ 0 ] === this.$element[ 0 ] ||
// Check the mousedown occurred inside the handle
OO.ui.contains( this.$handle[ 0 ], e.target, true );
};
/**
* Respond to dragstart event.
*
* @private
* @param {jQuery.Event} e Drag event
* @return {boolean} False if the event is cancelled
* @fires dragstart
*/
OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
var element = this,
dataTransfer = e.originalEvent.dataTransfer;
if ( !this.wasHandleUsed ) {
return false;
}
// Define drop effect
dataTransfer.dropEffect = 'none';
dataTransfer.effectAllowed = 'move';
// Support: Firefox
// We must set up a dataTransfer data property or Firefox seems to
// ignore the fact the element is draggable.
try {
dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
} catch ( err ) {
// The above is only for Firefox. Move on if it fails.
}
// Briefly add a 'clone' class to style the browser's native drag image
this.$element.addClass( 'oo-ui-draggableElement-clone' );
// Add placeholder class after the browser has rendered the clone
setTimeout( function () {
element.$element
.removeClass( 'oo-ui-draggableElement-clone' )
.addClass( 'oo-ui-draggableElement-placeholder' );
} );
// Emit event
this.emit( 'dragstart', this );
return true;
};
/**
* Respond to dragend event.
*
* @private
* @fires dragend
*/
OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
this.$element.removeClass( 'oo-ui-draggableElement-placeholder' );
this.emit( 'dragend' );
};
/**
* Handle drop event.
*
* @private
* @param {jQuery.Event} e Drop event
* @fires drop
*/
OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
e.preventDefault();
this.emit( 'drop', e );
};
/**
* In order for drag/drop to work, the dragover event must
* return false and stop propogation.
*
* @param {jQuery.Event} e Drag event
* @private
*/
OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
e.preventDefault();
};
/**
* Set item index.
* Store it in the DOM so we can access from the widget drag event
*
* @private
* @param {number} index Item index
*/
OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
if ( this.index !== index ) {
this.index = index;
this.$element.data( 'index', index );
}
};
/**
* Get item index
*
* @private
* @return {number} Item index
*/
OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
return this.index;
};
/**
* DraggableGroupElement is a mixin class used to create a group element to
* contain draggable elements, which are items that can be clicked and dragged by a mouse.
* The class is used with OO.ui.mixin.DraggableElement.
*
* @abstract
* @class
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
* should match the layout of the items. Items displayed in a single row
* or in several rows should use horizontal orientation. The vertical orientation should only be
* used when the items are displayed in a single column. Defaults to 'vertical'
*/
OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.orientation = config.orientation || 'vertical';
this.dragItem = null;
this.itemKeys = {};
this.dir = null;
this.itemsOrder = null;
// Events
this.aggregate( {
dragstart: 'itemDragStart',
dragend: 'itemDragEnd',
drop: 'itemDrop'
} );
this.connect( this, {
itemDragStart: 'onItemDragStart',
itemDrop: 'onItemDropOrDragEnd',
itemDragEnd: 'onItemDropOrDragEnd'
} );
// Initialize
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
this.$element
.addClass( 'oo-ui-draggableGroupElement' )
.attr( 'role', 'listbox' )
.append( this.$status )
.toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' );
};
/* Setup */
OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
/* Events */
/**
* An item has been dragged to a new position, but not yet dropped.
*
* @event drag
* @param {OO.ui.mixin.DraggableElement} item Dragged item
* @param {number} [newIndex] New index for the item
*/
/**
* And item has been dropped at a new position.
*
* @event reorder
* @param {OO.ui.mixin.DraggableElement} item Reordered item
* @param {number} [newIndex] New index for the item
*/
/* Methods */
/**
* Respond to item drag start event
*
* @private
* @param {OO.ui.mixin.DraggableElement} item Dragged item
*/
OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
// Make a shallow copy of this.items so we can re-order it during previews
// without affecting the original array.
this.itemsOrder = this.items.slice();
this.updateIndexes();
if ( this.orientation === 'horizontal' ) {
// Calculate and cache directionality on drag start - it's a little
// expensive and it shouldn't change while dragging.
this.dir = this.$element.css( 'direction' );
}
this.setDragItem( item );
};
/**
* Update the index properties of the items
*/
OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () {
var i, len;
// Map the index of each object
for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) {
this.itemsOrder[ i ].setIndex( i );
}
};
/**
* Handle drop or dragend event and switch the order of the items accordingly
*
* @private
* @param {OO.ui.mixin.DraggableElement} item Dropped item
*/
OO.ui.mixin.DraggableGroupElement.prototype.onItemDropOrDragEnd = function () {
var targetIndex, originalIndex,
item = this.getDragItem();
// TODO: Figure out a way to configure a list of legally droppable
// elements even if they are not yet in the list
if ( item ) {
originalIndex = this.items.indexOf( item );
// If the item has moved forward, add one to the index to account for the left shift
targetIndex = item.getIndex() + ( item.getIndex() > originalIndex ? 1 : 0 );
if ( targetIndex !== originalIndex ) {
this.reorder( this.getDragItem(), targetIndex );
this.emit( 'reorder', this.getDragItem(), targetIndex );
}
this.updateIndexes();
}
this.unsetDragItem();
// Return false to prevent propogation
return false;
};
/**
* Respond to dragover event
*
* @private
* @param {jQuery.Event} e Dragover event
* @fires reorder
*/
OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
var overIndex, targetIndex,
item = this.getDragItem(),
dragItemIndex = item.getIndex();
// Get the OptionWidget item we are dragging over
overIndex = $( e.target ).closest( '.oo-ui-draggableElement' ).data( 'index' );
if ( overIndex !== undefined && overIndex !== dragItemIndex ) {
targetIndex = overIndex + ( overIndex > dragItemIndex ? 1 : 0 );
if ( targetIndex > 0 ) {
this.$group.children().eq( targetIndex - 1 ).after( item.$element );
} else {
this.$group.prepend( item.$element );
}
// Move item in itemsOrder array
this.itemsOrder.splice( overIndex, 0,
this.itemsOrder.splice( dragItemIndex, 1 )[ 0 ]
);
this.updateIndexes();
this.emit( 'drag', item, targetIndex );
}
// Prevent default
e.preventDefault();
};
/**
* Reorder the items in the group
*
* @param {OO.ui.mixin.DraggableElement} item Reordered item
* @param {number} newIndex New index
*/
OO.ui.mixin.DraggableGroupElement.prototype.reorder = function ( item, newIndex ) {
this.addItems( [ item ], newIndex );
};
/**
* Set a dragged item
*
* @param {OO.ui.mixin.DraggableElement} item Dragged item
*/
OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
if ( this.dragItem !== item ) {
this.dragItem = item;
this.$element.on( 'dragover', this.onDragOver.bind( this ) );
this.$element.addClass( 'oo-ui-draggableGroupElement-dragging' );
}
};
/**
* Unset the current dragged item
*/
OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
if ( this.dragItem ) {
this.dragItem = null;
this.$element.off( 'dragover' );
this.$element.removeClass( 'oo-ui-draggableGroupElement-dragging' );
}
};
/**
* Get the item that is currently being dragged.
*
* @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
*/
OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
return this.dragItem;
};
/**
* RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
* the {@link OO.ui.mixin.LookupElement}.
*
* @class
* @abstract
*
* @constructor
*/
OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
this.requestCache = {};
this.requestQuery = null;
this.requestRequest = null;
};
/* Setup */
OO.initClass( OO.ui.mixin.RequestManager );
/**
* Get request results for the current query.
*
* @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
* the done event. If the request was aborted to make way for a subsequent request, this promise
* may not be rejected, depending on what jQuery feels like doing.
*/
OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
var widget = this,
value = this.getRequestQuery(),
deferred = $.Deferred(),
ourRequest;
this.abortRequest();
if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
deferred.resolve( this.requestCache[ value ] );
} else {
if ( this.pushPending ) {
this.pushPending();
}
this.requestQuery = value;
ourRequest = this.requestRequest = this.getRequest();
ourRequest
.always( function () {
// We need to pop pending even if this is an old request, otherwise
// the widget will remain pending forever.
// TODO: this assumes that an aborted request will fail or succeed soon after
// being aborted, or at least eventually. It would be nice if we could popPending()
// at abort time, but only if we knew that we hadn't already called popPending()
// for that request.
if ( widget.popPending ) {
widget.popPending();
}
} )
.done( function ( response ) {
// If this is an old request (and aborting it somehow caused it to still succeed),
// ignore its success completely
if ( ourRequest === widget.requestRequest ) {
widget.requestQuery = null;
widget.requestRequest = null;
widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
deferred.resolve( widget.requestCache[ value ] );
}
} )
.fail( function () {
// If this is an old request (or a request failing because it's being aborted),
// ignore its failure completely
if ( ourRequest === widget.requestRequest ) {
widget.requestQuery = null;
widget.requestRequest = null;
deferred.reject();
}
} );
}
return deferred.promise();
};
/**
* Abort the currently pending request, if any.
*
* @private
*/
OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
var oldRequest = this.requestRequest;
if ( oldRequest ) {
// First unset this.requestRequest to the fail handler will notice
// that the request is no longer current
this.requestRequest = null;
this.requestQuery = null;
oldRequest.abort();
}
};
/**
* Get the query to be made.
*
* @protected
* @method
* @abstract
* @return {string} query to be used
*/
OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
/**
* Get a new request object of the current query value.
*
* @protected
* @method
* @abstract
* @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
*/
OO.ui.mixin.RequestManager.prototype.getRequest = null;
/**
* Pre-process data returned by the request from #getRequest.
*
* The return value of this function will be cached, and any further queries for the given value
* will use the cache rather than doing API requests.
*
* @protected
* @method
* @abstract
* @param {Mixed} response Response from server
* @return {Mixed} Cached result data
*/
OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
/**
* LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
* a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
* into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
* from the lookup menu, that value becomes the value of the input field.
*
* Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
* not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
* re-enable lookups.
*
* See the [OOjs UI demos][1] for an example.
*
* [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
*
* @class
* @abstract
* @mixins OO.ui.mixin.RequestManager
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
* @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
* @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
* By default, the lookup menu is not generated and displayed until the user begins to type.
* @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
* take it over into the input with simply pressing return) automatically or not.
*/
OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
// Configuration initialization
config = $.extend( { highlightFirst: true }, config );
// Mixin constructors
OO.ui.mixin.RequestManager.call( this, config );
// Properties
this.$overlay = config.$overlay || this.$element;
this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
widget: this,
input: this,
$container: config.$container || this.$element
} );
this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
this.lookupsDisabled = false;
this.lookupInputFocused = false;
this.lookupHighlightFirstItem = config.highlightFirst;
// Events
this.$input.on( {
focus: this.onLookupInputFocus.bind( this ),
blur: this.onLookupInputBlur.bind( this ),
mousedown: this.onLookupInputMouseDown.bind( this )
} );
this.connect( this, { change: 'onLookupInputChange' } );
this.lookupMenu.connect( this, {
toggle: 'onLookupMenuToggle',
choose: 'onLookupMenuItemChoose'
} );
// Initialization
this.$element.addClass( 'oo-ui-lookupElement' );
this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
this.$overlay.append( this.lookupMenu.$element );
};
/* Setup */
OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
/* Methods */
/**
* Handle input focus event.
*
* @protected
* @param {jQuery.Event} e Input focus event
*/
OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
this.lookupInputFocused = true;
this.populateLookupMenu();
};
/**
* Handle input blur event.
*
* @protected
* @param {jQuery.Event} e Input blur event
*/
OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
this.closeLookupMenu();
this.lookupInputFocused = false;
};
/**
* Handle input mouse down event.
*
* @protected
* @param {jQuery.Event} e Input mouse down event
*/
OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
// Only open the menu if the input was already focused.
// This way we allow the user to open the menu again after closing it with Esc
// by clicking in the input. Opening (and populating) the menu when initially
// clicking into the input is handled by the focus handler.
if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
this.populateLookupMenu();
}
};
/**
* Handle input change event.
*
* @protected
* @param {string} value New input value
*/
OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
if ( this.lookupInputFocused ) {
this.populateLookupMenu();
}
};
/**
* Handle the lookup menu being shown/hidden.
*
* @protected
* @param {boolean} visible Whether the lookup menu is now visible.
*/
OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
if ( !visible ) {
// When the menu is hidden, abort any active request and clear the menu.
// This has to be done here in addition to closeLookupMenu(), because
// MenuSelectWidget will close itself when the user presses Esc.
this.abortLookupRequest();
this.lookupMenu.clearItems();
}
};
/**
* Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
*
* @protected
* @param {OO.ui.MenuOptionWidget} item Selected item
*/
OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
this.setValue( item.getData() );
};
/**
* Get lookup menu.
*
* @private
* @return {OO.ui.FloatingMenuSelectWidget}
*/
OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
return this.lookupMenu;
};
/**
* Disable or re-enable lookups.
*
* When lookups are disabled, calls to #populateLookupMenu will be ignored.
*
* @param {boolean} disabled Disable lookups
*/
OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
this.lookupsDisabled = !!disabled;
};
/**
* Open the menu. If there are no entries in the menu, this does nothing.
*
* @private
* @chainable
*/
OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
if ( !this.lookupMenu.isEmpty() ) {
this.lookupMenu.toggle( true );
}
return this;
};
/**
* Close the menu, empty it, and abort any pending request.
*
* @private
* @chainable
*/
OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
this.lookupMenu.toggle( false );
this.abortLookupRequest();
this.lookupMenu.clearItems();
return this;
};
/**
* Request menu items based on the input's current value, and when they arrive,
* populate the menu with these items and show the menu.
*
* If lookups have been disabled with #setLookupsDisabled, this function does nothing.
*
* @private
* @chainable
*/
OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
var widget = this,
value = this.getValue();
if ( this.lookupsDisabled || this.isReadOnly() ) {
return;
}
// If the input is empty, clear the menu, unless suggestions when empty are allowed.
if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
this.closeLookupMenu();
// Skip population if there is already a request pending for the current value
} else if ( value !== this.lookupQuery ) {
this.getLookupMenuItems()
.done( function ( items ) {
widget.lookupMenu.clearItems();
if ( items.length ) {
widget.lookupMenu
.addItems( items )
.toggle( true );
widget.initializeLookupMenuSelection();
} else {
widget.lookupMenu.toggle( false );
}
} )
.fail( function () {
widget.lookupMenu.clearItems();
} );
}
return this;
};
/**
* Highlight the first selectable item in the menu, if configured.
*
* @private
* @chainable
*/
OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
}
};
/**
* Get lookup menu items for the current query.
*
* @private
* @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
* the done event. If the request was aborted to make way for a subsequent request, this promise
* will not be rejected: it will remain pending forever.
*/
OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
return this.getRequestData().then( function ( data ) {
return this.getLookupMenuOptionsFromData( data );
}.bind( this ) );
};
/**
* Abort the currently pending lookup request, if any.
*
* @private
*/
OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
this.abortRequest();
};
/**
* Get a new request object of the current lookup query value.
*
* @protected
* @method
* @abstract
* @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
*/
OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
/**
* Pre-process data returned by the request from #getLookupRequest.
*
* The return value of this function will be cached, and any further queries for the given value
* will use the cache rather than doing API requests.
*
* @protected
* @method
* @abstract
* @param {Mixed} response Response from server
* @return {Mixed} Cached result data
*/
OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
/**
* Get a list of menu option widgets from the (possibly cached) data returned by
* #getLookupCacheDataFromResponse.
*
* @protected
* @method
* @abstract
* @param {Mixed} data Cached result data, usually an array
* @return {OO.ui.MenuOptionWidget[]} Menu items
*/
OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
/**
* Set the read-only state of the widget.
*
* This will also disable/enable the lookups functionality.
*
* @param {boolean} readOnly Make input read-only
* @chainable
*/
OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
// Parent method
// Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
// During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
if ( this.isReadOnly() && this.lookupMenu ) {
this.closeLookupMenu();
}
return this;
};
/**
* @inheritdoc OO.ui.mixin.RequestManager
*/
OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
return this.getValue();
};
/**
* @inheritdoc OO.ui.mixin.RequestManager
*/
OO.ui.mixin.LookupElement.prototype.getRequest = function () {
return this.getLookupRequest();
};
/**
* @inheritdoc OO.ui.mixin.RequestManager
*/
OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
return this.getLookupCacheDataFromResponse( response );
};
/**
* CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
* from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
* rather extended to include the required content and functionality.
*
* Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
* item is customized (with a label) using the #setupTabItem method. See
* {@link OO.ui.IndexLayout IndexLayout} for an example.
*
* @class
* @extends OO.ui.PanelLayout
*
* @constructor
* @param {string} name Unique symbolic name of card
* @param {Object} [config] Configuration options
* @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
*/
OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( name ) && config === undefined ) {
config = name;
name = config.name;
}
// Configuration initialization
config = $.extend( { scrollable: true }, config );
// Parent constructor
OO.ui.CardLayout.parent.call( this, config );
// Properties
this.name = name;
this.label = config.label;
this.tabItem = null;
this.active = false;
// Initialization
this.$element.addClass( 'oo-ui-cardLayout' );
};
/* Setup */
OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
/* Events */
/**
* An 'active' event is emitted when the card becomes active. Cards become active when they are
* shown in a index layout that is configured to display only one card at a time.
*
* @event active
* @param {boolean} active Card is active
*/
/* Methods */
/**
* Get the symbolic name of the card.
*
* @return {string} Symbolic name of card
*/
OO.ui.CardLayout.prototype.getName = function () {
return this.name;
};
/**
* Check if card is active.
*
* Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
* only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
*
* @return {boolean} Card is active
*/
OO.ui.CardLayout.prototype.isActive = function () {
return this.active;
};
/**
* Get tab item.
*
* The tab item allows users to access the card from the index's tab
* navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
*
* @return {OO.ui.TabOptionWidget|null} Tab option widget
*/
OO.ui.CardLayout.prototype.getTabItem = function () {
return this.tabItem;
};
/**
* Set or unset the tab item.
*
* Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
* or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
* level), use #setupTabItem instead of this method.
*
* @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
* @chainable
*/
OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
this.tabItem = tabItem || null;
if ( tabItem ) {
this.setupTabItem();
}
return this;
};
/**
* Set up the tab item.
*
* Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
* the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
* the #setTabItem method instead.
*
* @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
* @chainable
*/
OO.ui.CardLayout.prototype.setupTabItem = function () {
if ( this.label ) {
this.tabItem.setLabel( this.label );
}
return this;
};
/**
* Set the card to its 'active' state.
*
* Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
* CSS is applied to the tab item to reflect the card's active state. Outside of the index
* context, setting the active state on a card does nothing.
*
* @param {boolean} active Card is active
* @fires active
*/
OO.ui.CardLayout.prototype.setActive = function ( active ) {
active = !!active;
if ( active !== this.active ) {
this.active = active;
this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
this.emit( 'active', this.active );
}
};
/**
* PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
* from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
* rather extended to include the required content and functionality.
*
* Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
* item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
* {@link OO.ui.BookletLayout BookletLayout} for an example.
*
* @class
* @extends OO.ui.PanelLayout
*
* @constructor
* @param {string} name Unique symbolic name of page
* @param {Object} [config] Configuration options
*/
OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( name ) && config === undefined ) {
config = name;
name = config.name;
}
// Configuration initialization
config = $.extend( { scrollable: true }, config );
// Parent constructor
OO.ui.PageLayout.parent.call( this, config );
// Properties
this.name = name;
this.outlineItem = null;
this.active = false;
// Initialization
this.$element.addClass( 'oo-ui-pageLayout' );
};
/* Setup */
OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
/* Events */
/**
* An 'active' event is emitted when the page becomes active. Pages become active when they are
* shown in a booklet layout that is configured to display only one page at a time.
*
* @event active
* @param {boolean} active Page is active
*/
/* Methods */
/**
* Get the symbolic name of the page.
*
* @return {string} Symbolic name of page
*/
OO.ui.PageLayout.prototype.getName = function () {
return this.name;
};
/**
* Check if page is active.
*
* Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
* only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
*
* @return {boolean} Page is active
*/
OO.ui.PageLayout.prototype.isActive = function () {
return this.active;
};
/**
* Get outline item.
*
* The outline item allows users to access the page from the booklet's outline
* navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
*
* @return {OO.ui.OutlineOptionWidget|null} Outline option widget
*/
OO.ui.PageLayout.prototype.getOutlineItem = function () {
return this.outlineItem;
};
/**
* Set or unset the outline item.
*
* Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
* or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
* level), use #setupOutlineItem instead of this method.
*
* @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
* @chainable
*/
OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
this.outlineItem = outlineItem || null;
if ( outlineItem ) {
this.setupOutlineItem();
}
return this;
};
/**
* Set up the outline item.
*
* Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
* the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
* the #setOutlineItem method instead.
*
* @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
* @chainable
*/
OO.ui.PageLayout.prototype.setupOutlineItem = function () {
return this;
};
/**
* Set the page to its 'active' state.
*
* Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
* CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
* context, setting the active state on a page does nothing.
*
* @param {boolean} active Page is active
* @fires active
*/
OO.ui.PageLayout.prototype.setActive = function ( active ) {
active = !!active;
if ( active !== this.active ) {
this.active = active;
this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
this.emit( 'active', this.active );
}
};
/**
* StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
* at a time, though the stack layout can also be configured to show all contained panels, one after another,
* by setting the #continuous option to 'true'.
*
* @example
* // A stack layout with two panels, configured to be displayed continously
* var myStack = new OO.ui.StackLayout( {
* items: [
* new OO.ui.PanelLayout( {
* $content: $( '<p>Panel One</p>' ),
* padded: true,
* framed: true
* } ),
* new OO.ui.PanelLayout( {
* $content: $( '<p>Panel Two</p>' ),
* padded: true,
* framed: true
* } )
* ],
* continuous: true
* } );
* $( 'body' ).append( myStack.$element );
*
* @class
* @extends OO.ui.PanelLayout
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
* @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
*/
OO.ui.StackLayout = function OoUiStackLayout( config ) {
// Configuration initialization
config = $.extend( { scrollable: true }, config );
// Parent constructor
OO.ui.StackLayout.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
// Properties
this.currentItem = null;
this.continuous = !!config.continuous;
// Initialization
this.$element.addClass( 'oo-ui-stackLayout' );
if ( this.continuous ) {
this.$element.addClass( 'oo-ui-stackLayout-continuous' );
this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
}
if ( Array.isArray( config.items ) ) {
this.addItems( config.items );
}
};
/* Setup */
OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
/* Events */
/**
* A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
* {@link #clearItems cleared} or {@link #setItem displayed}.
*
* @event set
* @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
*/
/**
* When used in continuous mode, this event is emitted when the user scrolls down
* far enough such that currentItem is no longer visible.
*
* @event visibleItemChange
* @param {OO.ui.PanelLayout} panel The next visible item in the layout
*/
/* Methods */
/**
* Handle scroll events from the layout element
*
* @param {jQuery.Event} e
* @fires visibleItemChange
*/
OO.ui.StackLayout.prototype.onScroll = function () {
var currentRect,
len = this.items.length,
currentIndex = this.items.indexOf( this.currentItem ),
newIndex = currentIndex,
containerRect = this.$element[ 0 ].getBoundingClientRect();
if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
// Can't get bounding rect, possibly not attached.
return;
}
function getRect( item ) {
return item.$element[ 0 ].getBoundingClientRect();
}
function isVisible( item ) {
var rect = getRect( item );
return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
}
currentRect = getRect( this.currentItem );
if ( currentRect.bottom < containerRect.top ) {
// Scrolled down past current item
while ( ++newIndex < len ) {
if ( isVisible( this.items[ newIndex ] ) ) {
break;
}
}
} else if ( currentRect.top > containerRect.bottom ) {
// Scrolled up past current item
while ( --newIndex >= 0 ) {
if ( isVisible( this.items[ newIndex ] ) ) {
break;
}
}
}
if ( newIndex !== currentIndex ) {
this.emit( 'visibleItemChange', this.items[ newIndex ] );
}
};
/**
* Get the current panel.
*
* @return {OO.ui.Layout|null}
*/
OO.ui.StackLayout.prototype.getCurrentItem = function () {
return this.currentItem;
};
/**
* Unset the current item.
*
* @private
* @param {OO.ui.StackLayout} layout
* @fires set
*/
OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
var prevItem = this.currentItem;
if ( prevItem === null ) {
return;
}
this.currentItem = null;
this.emit( 'set', null );
};
/**
* Add panel layouts to the stack layout.
*
* Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
* insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
* by the index.
*
* @param {OO.ui.Layout[]} items Panels to add
* @param {number} [index] Index of the insertion point
* @chainable
*/
OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
// Update the visibility
this.updateHiddenState( items, this.currentItem );
// Mixin method
OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
if ( !this.currentItem && items.length ) {
this.setItem( items[ 0 ] );
}
return this;
};
/**
* Remove the specified panels from the stack layout.
*
* Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
* you may wish to use the #clearItems method instead.
*
* @param {OO.ui.Layout[]} items Panels to remove
* @chainable
* @fires set
*/
OO.ui.StackLayout.prototype.removeItems = function ( items ) {
// Mixin method
OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
if ( items.indexOf( this.currentItem ) !== -1 ) {
if ( this.items.length ) {
this.setItem( this.items[ 0 ] );
} else {
this.unsetCurrentItem();
}
}
return this;
};
/**
* Clear all panels from the stack layout.
*
* Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
* a subset of panels, use the #removeItems method.
*
* @chainable
* @fires set
*/
OO.ui.StackLayout.prototype.clearItems = function () {
this.unsetCurrentItem();
OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
return this;
};
/**
* Show the specified panel.
*
* If another panel is currently displayed, it will be hidden.
*
* @param {OO.ui.Layout} item Panel to show
* @chainable
* @fires set
*/
OO.ui.StackLayout.prototype.setItem = function ( item ) {
if ( item !== this.currentItem ) {
this.updateHiddenState( this.items, item );
if ( this.items.indexOf( item ) !== -1 ) {
this.currentItem = item;
this.emit( 'set', item );
} else {
this.unsetCurrentItem();
}
}
return this;
};
/**
* Update the visibility of all items in case of non-continuous view.
*
* Ensure all items are hidden except for the selected one.
* This method does nothing when the stack is continuous.
*
* @private
* @param {OO.ui.Layout[]} items Item list iterate over
* @param {OO.ui.Layout} [selectedItem] Selected item to show
*/
OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
var i, len;
if ( !this.continuous ) {
for ( i = 0, len = items.length; i < len; i++ ) {
if ( !selectedItem || selectedItem !== items[ i ] ) {
items[ i ].$element.addClass( 'oo-ui-element-hidden' );
items[ i ].$element.attr( 'aria-hidden', 'true' );
}
}
if ( selectedItem ) {
selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
selectedItem.$element.removeAttr( 'aria-hidden' );
}
}
};
/**
* MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom)
* and its size is customized with the #menuSize config. The content area will fill all remaining space.
*
* @example
* var menuLayout = new OO.ui.MenuLayout( {
* position: 'top'
* } ),
* menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
* contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
* select = new OO.ui.SelectWidget( {
* items: [
* new OO.ui.OptionWidget( {
* data: 'before',
* label: 'Before',
* } ),
* new OO.ui.OptionWidget( {
* data: 'after',
* label: 'After',
* } ),
* new OO.ui.OptionWidget( {
* data: 'top',
* label: 'Top',
* } ),
* new OO.ui.OptionWidget( {
* data: 'bottom',
* label: 'Bottom',
* } )
* ]
* } ).on( 'select', function ( item ) {
* menuLayout.setMenuPosition( item.getData() );
* } );
*
* menuLayout.$menu.append(
* menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
* );
* menuLayout.$content.append(
* contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
* );
* $( 'body' ).append( menuLayout.$element );
*
* If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
* below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
* menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
* may be omitted.
*
* .oo-ui-menuLayout-menu {
* height: 200px;
* width: 200px;
* }
* .oo-ui-menuLayout-content {
* top: 200px;
* left: 200px;
* right: 200px;
* bottom: 200px;
* }
*
* @class
* @extends OO.ui.Layout
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [showMenu=true] Show menu
* @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
*/
OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
// Configuration initialization
config = $.extend( {
showMenu: true,
menuPosition: 'before'
}, config );
// Parent constructor
OO.ui.MenuLayout.parent.call( this, config );
/**
* Menu DOM node
*
* @property {jQuery}
*/
this.$menu = $( '<div>' );
/**
* Content DOM node
*
* @property {jQuery}
*/
this.$content = $( '<div>' );
// Initialization
this.$menu
.addClass( 'oo-ui-menuLayout-menu' );
this.$content.addClass( 'oo-ui-menuLayout-content' );
this.$element
.addClass( 'oo-ui-menuLayout' )
.append( this.$content, this.$menu );
this.setMenuPosition( config.menuPosition );
this.toggleMenu( config.showMenu );
};
/* Setup */
OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
/* Methods */
/**
* Toggle menu.
*
* @param {boolean} showMenu Show menu, omit to toggle
* @chainable
*/
OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
if ( this.showMenu !== showMenu ) {
this.showMenu = showMenu;
this.$element
.toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
.toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' );
}
return this;
};
/**
* Check if menu is visible
*
* @return {boolean} Menu is visible
*/
OO.ui.MenuLayout.prototype.isMenuVisible = function () {
return this.showMenu;
};
/**
* Set menu position.
*
* @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
* @throws {Error} If position value is not supported
* @chainable
*/
OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
this.menuPosition = position;
this.$element.addClass( 'oo-ui-menuLayout-' + position );
return this;
};
/**
* Get menu position.
*
* @return {string} Menu position
*/
OO.ui.MenuLayout.prototype.getMenuPosition = function () {
return this.menuPosition;
};
/**
* BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
* an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
* through the pages and select which one to display. By default, only one page is
* displayed at a time and the outline is hidden. When a user navigates to a new page,
* the booklet layout automatically focuses on the first focusable element, unless the
* default setting is changed. Optionally, booklets can be configured to show
* {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
*
* @example
* // Example of a BookletLayout that contains two PageLayouts.
*
* function PageOneLayout( name, config ) {
* PageOneLayout.parent.call( this, name, config );
* this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
* }
* OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
* PageOneLayout.prototype.setupOutlineItem = function () {
* this.outlineItem.setLabel( 'Page One' );
* };
*
* function PageTwoLayout( name, config ) {
* PageTwoLayout.parent.call( this, name, config );
* this.$element.append( '<p>Second page</p>' );
* }
* OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
* PageTwoLayout.prototype.setupOutlineItem = function () {
* this.outlineItem.setLabel( 'Page Two' );
* };
*
* var page1 = new PageOneLayout( 'one' ),
* page2 = new PageTwoLayout( 'two' );
*
* var booklet = new OO.ui.BookletLayout( {
* outlined: true
* } );
*
* booklet.addPages ( [ page1, page2 ] );
* $( 'body' ).append( booklet.$element );
*
* @class
* @extends OO.ui.MenuLayout
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [continuous=false] Show all pages, one after another
* @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
* @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
* @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
*/
OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.BookletLayout.parent.call( this, config );
// Properties
this.currentPageName = null;
this.pages = {};
this.ignoreFocus = false;
this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
this.$content.append( this.stackLayout.$element );
this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
this.outlineVisible = false;
this.outlined = !!config.outlined;
if ( this.outlined ) {
this.editable = !!config.editable;
this.outlineControlsWidget = null;
this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
this.$menu.append( this.outlinePanel.$element );
this.outlineVisible = true;
if ( this.editable ) {
this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
this.outlineSelectWidget
);
}
}
this.toggleMenu( this.outlined );
// Events
this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
if ( this.outlined ) {
this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
this.scrolling = false;
this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
}
if ( this.autoFocus ) {
// Event 'focus' does not bubble, but 'focusin' does
this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
}
// Initialization
this.$element.addClass( 'oo-ui-bookletLayout' );
this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
if ( this.outlined ) {
this.outlinePanel.$element
.addClass( 'oo-ui-bookletLayout-outlinePanel' )
.append( this.outlineSelectWidget.$element );
if ( this.editable ) {
this.outlinePanel.$element
.addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
.append( this.outlineControlsWidget.$element );
}
}
};
/* Setup */
OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
/* Events */
/**
* A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
* @event set
* @param {OO.ui.PageLayout} page Current page
*/
/**
* An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
*
* @event add
* @param {OO.ui.PageLayout[]} page Added pages
* @param {number} index Index pages were added at
*/
/**
* A 'remove' event is emitted when pages are {@link #clearPages cleared} or
* {@link #removePages removed} from the booklet.
*
* @event remove
* @param {OO.ui.PageLayout[]} pages Removed pages
*/
/* Methods */
/**
* Handle stack layout focus.
*
* @private
* @param {jQuery.Event} e Focusin event
*/
OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
var name, $target;
// Find the page that an element was focused within
$target = $( e.target ).closest( '.oo-ui-pageLayout' );
for ( name in this.pages ) {
// Check for page match, exclude current page to find only page changes
if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
this.setPage( name );
break;
}
}
};
/**
* Handle visibleItemChange events from the stackLayout
*
* The next visible page is set as the current page by selecting it
* in the outline
*
* @param {OO.ui.PageLayout} page The next visible page in the layout
*/
OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
// Set a flag to so that the resulting call to #onStackLayoutSet doesn't
// try and scroll the item into view again.
this.scrolling = true;
this.outlineSelectWidget.selectItemByData( page.getName() );
this.scrolling = false;
};
/**
* Handle stack layout set events.
*
* @private
* @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
*/
OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
var layout = this;
if ( !this.scrolling && page ) {
page.scrollElementIntoView().done( function () {
if ( layout.autoFocus && !OO.ui.isMobile() ) {
layout.focus();
}
} );
}
};
/**
* Focus the first input in the current page.
*
* If no page is selected, the first selectable page will be selected.
* If the focus is already in an element on the current page, nothing will happen.
*
* @param {number} [itemIndex] A specific item to focus on
*/
OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
var page,
items = this.stackLayout.getItems();
if ( itemIndex !== undefined && items[ itemIndex ] ) {
page = items[ itemIndex ];
} else {
page = this.stackLayout.getCurrentItem();
}
if ( !page && this.outlined ) {
this.selectFirstSelectablePage();
page = this.stackLayout.getCurrentItem();
}
if ( !page ) {
return;
}
// Only change the focus if is not already in the current page
if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
page.focus();
}
};
/**
* Find the first focusable input in the booklet layout and focus
* on it.
*/
OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
OO.ui.findFocusable( this.stackLayout.$element ).focus();
};
/**
* Handle outline widget select events.
*
* @private
* @param {OO.ui.OptionWidget|null} item Selected item
*/
OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
if ( item ) {
this.setPage( item.getData() );
}
};
/**
* Check if booklet has an outline.
*
* @return {boolean} Booklet has an outline
*/
OO.ui.BookletLayout.prototype.isOutlined = function () {
return this.outlined;
};
/**
* Check if booklet has editing controls.
*
* @return {boolean} Booklet is editable
*/
OO.ui.BookletLayout.prototype.isEditable = function () {
return this.editable;
};
/**
* Check if booklet has a visible outline.
*
* @return {boolean} Outline is visible
*/
OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
return this.outlined && this.outlineVisible;
};
/**
* Hide or show the outline.
*
* @param {boolean} [show] Show outline, omit to invert current state
* @chainable
*/
OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
if ( this.outlined ) {
show = show === undefined ? !this.outlineVisible : !!show;
this.outlineVisible = show;
this.toggleMenu( show );
}
return this;
};
/**
* Get the page closest to the specified page.
*
* @param {OO.ui.PageLayout} page Page to use as a reference point
* @return {OO.ui.PageLayout|null} Page closest to the specified page
*/
OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
var next, prev, level,
pages = this.stackLayout.getItems(),
index = pages.indexOf( page );
if ( index !== -1 ) {
next = pages[ index + 1 ];
prev = pages[ index - 1 ];
// Prefer adjacent pages at the same level
if ( this.outlined ) {
level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
if (
prev &&
level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
) {
return prev;
}
if (
next &&
level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
) {
return next;
}
}
}
return prev || next || null;
};
/**
* Get the outline widget.
*
* If the booklet is not outlined, the method will return `null`.
*
* @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
*/
OO.ui.BookletLayout.prototype.getOutline = function () {
return this.outlineSelectWidget;
};
/**
* Get the outline controls widget.
*
* If the outline is not editable, the method will return `null`.
*
* @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
*/
OO.ui.BookletLayout.prototype.getOutlineControls = function () {
return this.outlineControlsWidget;
};
/**
* Get a page by its symbolic name.
*
* @param {string} name Symbolic name of page
* @return {OO.ui.PageLayout|undefined} Page, if found
*/
OO.ui.BookletLayout.prototype.getPage = function ( name ) {
return this.pages[ name ];
};
/**
* Get the current page.
*
* @return {OO.ui.PageLayout|undefined} Current page, if found
*/
OO.ui.BookletLayout.prototype.getCurrentPage = function () {
var name = this.getCurrentPageName();
return name ? this.getPage( name ) : undefined;
};
/**
* Get the symbolic name of the current page.
*
* @return {string|null} Symbolic name of the current page
*/
OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
return this.currentPageName;
};
/**
* Add pages to the booklet layout
*
* When pages are added with the same names as existing pages, the existing pages will be
* automatically removed before the new pages are added.
*
* @param {OO.ui.PageLayout[]} pages Pages to add
* @param {number} index Index of the insertion point
* @fires add
* @chainable
*/
OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
var i, len, name, page, item, currentIndex,
stackLayoutPages = this.stackLayout.getItems(),
remove = [],
items = [];
// Remove pages with same names
for ( i = 0, len = pages.length; i < len; i++ ) {
page = pages[ i ];
name = page.getName();
if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
// Correct the insertion index
currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
if ( currentIndex !== -1 && currentIndex + 1 < index ) {
index--;
}
remove.push( this.pages[ name ] );
}
}
if ( remove.length ) {
this.removePages( remove );
}
// Add new pages
for ( i = 0, len = pages.length; i < len; i++ ) {
page = pages[ i ];
name = page.getName();
this.pages[ page.getName() ] = page;
if ( this.outlined ) {
item = new OO.ui.OutlineOptionWidget( { data: name } );
page.setOutlineItem( item );
items.push( item );
}
}
if ( this.outlined && items.length ) {
this.outlineSelectWidget.addItems( items, index );
this.selectFirstSelectablePage();
}
this.stackLayout.addItems( pages, index );
this.emit( 'add', pages, index );
return this;
};
/**
* Remove the specified pages from the booklet layout.
*
* To remove all pages from the booklet, you may wish to use the #clearPages method instead.
*
* @param {OO.ui.PageLayout[]} pages An array of pages to remove
* @fires remove
* @chainable
*/
OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
var i, len, name, page,
items = [];
for ( i = 0, len = pages.length; i < len; i++ ) {
page = pages[ i ];
name = page.getName();
delete this.pages[ name ];
if ( this.outlined ) {
items.push( this.outlineSelectWidget.getItemFromData( name ) );
page.setOutlineItem( null );
}
}
if ( this.outlined && items.length ) {
this.outlineSelectWidget.removeItems( items );
this.selectFirstSelectablePage();
}
this.stackLayout.removeItems( pages );
this.emit( 'remove', pages );
return this;
};
/**
* Clear all pages from the booklet layout.
*
* To remove only a subset of pages from the booklet, use the #removePages method.
*
* @fires remove
* @chainable
*/
OO.ui.BookletLayout.prototype.clearPages = function () {
var i, len,
pages = this.stackLayout.getItems();
this.pages = {};
this.currentPageName = null;
if ( this.outlined ) {
this.outlineSelectWidget.clearItems();
for ( i = 0, len = pages.length; i < len; i++ ) {
pages[ i ].setOutlineItem( null );
}
}
this.stackLayout.clearItems();
this.emit( 'remove', pages );
return this;
};
/**
* Set the current page by symbolic name.
*
* @fires set
* @param {string} name Symbolic name of page
*/
OO.ui.BookletLayout.prototype.setPage = function ( name ) {
var selectedItem,
$focused,
page = this.pages[ name ],
previousPage = this.currentPageName && this.pages[ this.currentPageName ];
if ( name !== this.currentPageName ) {
if ( this.outlined ) {
selectedItem = this.outlineSelectWidget.getSelectedItem();
if ( selectedItem && selectedItem.getData() !== name ) {
this.outlineSelectWidget.selectItemByData( name );
}
}
if ( page ) {
if ( previousPage ) {
previousPage.setActive( false );
// Blur anything focused if the next page doesn't have anything focusable.
// This is not needed if the next page has something focusable (because once it is focused
// this blur happens automatically). If the layout is non-continuous, this check is
// meaningless because the next page is not visible yet and thus can't hold focus.
if (
this.autoFocus &&
!OO.ui.isMobile() &&
this.stackLayout.continuous &&
OO.ui.findFocusable( page.$element ).length !== 0
) {
$focused = previousPage.$element.find( ':focus' );
if ( $focused.length ) {
$focused[ 0 ].blur();
}
}
}
this.currentPageName = name;
page.setActive( true );
this.stackLayout.setItem( page );
if ( !this.stackLayout.continuous && previousPage ) {
// This should not be necessary, since any inputs on the previous page should have been
// blurred when it was hidden, but browsers are not very consistent about this.
$focused = previousPage.$element.find( ':focus' );
if ( $focused.length ) {
$focused[ 0 ].blur();
}
}
this.emit( 'set', page );
}
}
};
/**
* Select the first selectable page.
*
* @chainable
*/
OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
if ( !this.outlineSelectWidget.getSelectedItem() ) {
this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
}
return this;
};
/**
* IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
* {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
* select which one to display. By default, only one card is displayed at a time. When a user
* navigates to a new card, the index layout automatically focuses on the first focusable element,
* unless the default setting is changed.
*
* TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
*
* @example
* // Example of a IndexLayout that contains two CardLayouts.
*
* function CardOneLayout( name, config ) {
* CardOneLayout.parent.call( this, name, config );
* this.$element.append( '<p>First card</p>' );
* }
* OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
* CardOneLayout.prototype.setupTabItem = function () {
* this.tabItem.setLabel( 'Card one' );
* };
*
* var card1 = new CardOneLayout( 'one' ),
* card2 = new OO.ui.CardLayout( 'two', { label: 'Card two' } );
*
* card2.$element.append( '<p>Second card</p>' );
*
* var index = new OO.ui.IndexLayout();
*
* index.addCards ( [ card1, card2 ] );
* $( 'body' ).append( index.$element );
*
* @class
* @extends OO.ui.MenuLayout
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [continuous=false] Show all cards, one after another
* @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
* @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed. Disabled on mobile.
*/
OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
// Configuration initialization
config = $.extend( {}, config, { menuPosition: 'top' } );
// Parent constructor
OO.ui.IndexLayout.parent.call( this, config );
// Properties
this.currentCardName = null;
this.cards = {};
this.ignoreFocus = false;
this.stackLayout = new OO.ui.StackLayout( {
continuous: !!config.continuous,
expanded: config.expanded
} );
this.$content.append( this.stackLayout.$element );
this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
this.tabSelectWidget = new OO.ui.TabSelectWidget();
this.tabPanel = new OO.ui.PanelLayout();
this.$menu.append( this.tabPanel.$element );
this.toggleMenu( true );
// Events
this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
if ( this.autoFocus ) {
// Event 'focus' does not bubble, but 'focusin' does
this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
}
// Initialization
this.$element.addClass( 'oo-ui-indexLayout' );
this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
this.tabPanel.$element
.addClass( 'oo-ui-indexLayout-tabPanel' )
.append( this.tabSelectWidget.$element );
};
/* Setup */
OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
/* Events */
/**
* A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
* @event set
* @param {OO.ui.CardLayout} card Current card
*/
/**
* An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
*
* @event add
* @param {OO.ui.CardLayout[]} card Added cards
* @param {number} index Index cards were added at
*/
/**
* A 'remove' event is emitted when cards are {@link #clearCards cleared} or
* {@link #removeCards removed} from the index.
*
* @event remove
* @param {OO.ui.CardLayout[]} cards Removed cards
*/
/* Methods */
/**
* Handle stack layout focus.
*
* @private
* @param {jQuery.Event} e Focusin event
*/
OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
var name, $target;
// Find the card that an element was focused within
$target = $( e.target ).closest( '.oo-ui-cardLayout' );
for ( name in this.cards ) {
// Check for card match, exclude current card to find only card changes
if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
this.setCard( name );
break;
}
}
};
/**
* Handle stack layout set events.
*
* @private
* @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
*/
OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
var layout = this;
if ( card ) {
card.scrollElementIntoView().done( function () {
if ( layout.autoFocus && !OO.ui.isMobile() ) {
layout.focus();
}
} );
}
};
/**
* Focus the first input in the current card.
*
* If no card is selected, the first selectable card will be selected.
* If the focus is already in an element on the current card, nothing will happen.
*
* @param {number} [itemIndex] A specific item to focus on
*/
OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
var card,
items = this.stackLayout.getItems();
if ( itemIndex !== undefined && items[ itemIndex ] ) {
card = items[ itemIndex ];
} else {
card = this.stackLayout.getCurrentItem();
}
if ( !card ) {
this.selectFirstSelectableCard();
card = this.stackLayout.getCurrentItem();
}
if ( !card ) {
return;
}
// Only change the focus if is not already in the current page
if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
card.focus();
}
};
/**
* Find the first focusable input in the index layout and focus
* on it.
*/
OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
OO.ui.findFocusable( this.stackLayout.$element ).focus();
};
/**
* Handle tab widget select events.
*
* @private
* @param {OO.ui.OptionWidget|null} item Selected item
*/
OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
if ( item ) {
this.setCard( item.getData() );
}
};
/**
* Get the card closest to the specified card.
*
* @param {OO.ui.CardLayout} card Card to use as a reference point
* @return {OO.ui.CardLayout|null} Card closest to the specified card
*/
OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
var next, prev, level,
cards = this.stackLayout.getItems(),
index = cards.indexOf( card );
if ( index !== -1 ) {
next = cards[ index + 1 ];
prev = cards[ index - 1 ];
// Prefer adjacent cards at the same level
level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
if (
prev &&
level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
) {
return prev;
}
if (
next &&
level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
) {
return next;
}
}
return prev || next || null;
};
/**
* Get the tabs widget.
*
* @return {OO.ui.TabSelectWidget} Tabs widget
*/
OO.ui.IndexLayout.prototype.getTabs = function () {
return this.tabSelectWidget;
};
/**
* Get a card by its symbolic name.
*
* @param {string} name Symbolic name of card
* @return {OO.ui.CardLayout|undefined} Card, if found
*/
OO.ui.IndexLayout.prototype.getCard = function ( name ) {
return this.cards[ name ];
};
/**
* Get the current card.
*
* @return {OO.ui.CardLayout|undefined} Current card, if found
*/
OO.ui.IndexLayout.prototype.getCurrentCard = function () {
var name = this.getCurrentCardName();
return name ? this.getCard( name ) : undefined;
};
/**
* Get the symbolic name of the current card.
*
* @return {string|null} Symbolic name of the current card
*/
OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
return this.currentCardName;
};
/**
* Add cards to the index layout
*
* When cards are added with the same names as existing cards, the existing cards will be
* automatically removed before the new cards are added.
*
* @param {OO.ui.CardLayout[]} cards Cards to add
* @param {number} index Index of the insertion point
* @fires add
* @chainable
*/
OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
var i, len, name, card, item, currentIndex,
stackLayoutCards = this.stackLayout.getItems(),
remove = [],
items = [];
// Remove cards with same names
for ( i = 0, len = cards.length; i < len; i++ ) {
card = cards[ i ];
name = card.getName();
if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
// Correct the insertion index
currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
if ( currentIndex !== -1 && currentIndex + 1 < index ) {
index--;
}
remove.push( this.cards[ name ] );
}
}
if ( remove.length ) {
this.removeCards( remove );
}
// Add new cards
for ( i = 0, len = cards.length; i < len; i++ ) {
card = cards[ i ];
name = card.getName();
this.cards[ card.getName() ] = card;
item = new OO.ui.TabOptionWidget( { data: name } );
card.setTabItem( item );
items.push( item );
}
if ( items.length ) {
this.tabSelectWidget.addItems( items, index );
this.selectFirstSelectableCard();
}
this.stackLayout.addItems( cards, index );
this.emit( 'add', cards, index );
return this;
};
/**
* Remove the specified cards from the index layout.
*
* To remove all cards from the index, you may wish to use the #clearCards method instead.
*
* @param {OO.ui.CardLayout[]} cards An array of cards to remove
* @fires remove
* @chainable
*/
OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
var i, len, name, card,
items = [];
for ( i = 0, len = cards.length; i < len; i++ ) {
card = cards[ i ];
name = card.getName();
delete this.cards[ name ];
items.push( this.tabSelectWidget.getItemFromData( name ) );
card.setTabItem( null );
}
if ( items.length ) {
this.tabSelectWidget.removeItems( items );
this.selectFirstSelectableCard();
}
this.stackLayout.removeItems( cards );
this.emit( 'remove', cards );
return this;
};
/**
* Clear all cards from the index layout.
*
* To remove only a subset of cards from the index, use the #removeCards method.
*
* @fires remove
* @chainable
*/
OO.ui.IndexLayout.prototype.clearCards = function () {
var i, len,
cards = this.stackLayout.getItems();
this.cards = {};
this.currentCardName = null;
this.tabSelectWidget.clearItems();
for ( i = 0, len = cards.length; i < len; i++ ) {
cards[ i ].setTabItem( null );
}
this.stackLayout.clearItems();
this.emit( 'remove', cards );
return this;
};
/**
* Set the current card by symbolic name.
*
* @fires set
* @param {string} name Symbolic name of card
*/
OO.ui.IndexLayout.prototype.setCard = function ( name ) {
var selectedItem,
$focused,
card = this.cards[ name ],
previousCard = this.currentCardName && this.cards[ this.currentCardName ];
if ( name !== this.currentCardName ) {
selectedItem = this.tabSelectWidget.getSelectedItem();
if ( selectedItem && selectedItem.getData() !== name ) {
this.tabSelectWidget.selectItemByData( name );
}
if ( card ) {
if ( previousCard ) {
previousCard.setActive( false );
// Blur anything focused if the next card doesn't have anything focusable.
// This is not needed if the next card has something focusable (because once it is focused
// this blur happens automatically). If the layout is non-continuous, this check is
// meaningless because the next card is not visible yet and thus can't hold focus.
if (
this.autoFocus &&
!OO.ui.isMobile() &&
this.stackLayout.continuous &&
OO.ui.findFocusable( card.$element ).length !== 0
) {
$focused = previousCard.$element.find( ':focus' );
if ( $focused.length ) {
$focused[ 0 ].blur();
}
}
}
this.currentCardName = name;
card.setActive( true );
this.stackLayout.setItem( card );
if ( !this.stackLayout.continuous && previousCard ) {
// This should not be necessary, since any inputs on the previous card should have been
// blurred when it was hidden, but browsers are not very consistent about this.
$focused = previousCard.$element.find( ':focus' );
if ( $focused.length ) {
$focused[ 0 ].blur();
}
}
this.emit( 'set', card );
}
}
};
/**
* Select the first selectable card.
*
* @chainable
*/
OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
if ( !this.tabSelectWidget.getSelectedItem() ) {
this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
}
return this;
};
/**
* ToggleWidget implements basic behavior of widgets with an on/off state.
* Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
*
* @abstract
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [value=false] The toggle’s initial on/off state.
* By default, the toggle is in the 'off' state.
*/
OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ToggleWidget.parent.call( this, config );
// Properties
this.value = null;
// Initialization
this.$element.addClass( 'oo-ui-toggleWidget' );
this.setValue( !!config.value );
};
/* Setup */
OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
/* Events */
/**
* @event change
*
* A change event is emitted when the on/off state of the toggle changes.
*
* @param {boolean} value Value representing the new state of the toggle
*/
/* Methods */
/**
* Get the value representing the toggle’s state.
*
* @return {boolean} The on/off state of the toggle
*/
OO.ui.ToggleWidget.prototype.getValue = function () {
return this.value;
};
/**
* Set the state of the toggle: `true` for 'on', `false' for 'off'.
*
* @param {boolean} value The state of the toggle
* @fires change
* @chainable
*/
OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
value = !!value;
if ( this.value !== value ) {
this.value = value;
this.emit( 'change', value );
this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
this.$element.attr( 'aria-checked', value.toString() );
}
return this;
};
/**
* ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
* Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
* configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
* {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
* and {@link OO.ui.mixin.LabelElement labels}. Please see
* the [OOjs UI documentation][1] on MediaWiki for more information.
*
* @example
* // Toggle buttons in the 'off' and 'on' state.
* var toggleButton1 = new OO.ui.ToggleButtonWidget( {
* label: 'Toggle Button off'
* } );
* var toggleButton2 = new OO.ui.ToggleButtonWidget( {
* label: 'Toggle Button on',
* value: true
* } );
* // Append the buttons to the DOM.
* $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
*
* @class
* @extends OO.ui.ToggleWidget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [value=false] The toggle button’s initial on/off
* state. By default, the button is in the 'off' state.
*/
OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ToggleButtonWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
// Events
this.connect( this, { click: 'onAction' } );
// Initialization
this.$button.append( this.$icon, this.$label, this.$indicator );
this.$element
.addClass( 'oo-ui-toggleButtonWidget' )
.append( this.$button );
};
/* Setup */
OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Handle the button action being triggered.
*
* @private
*/
OO.ui.ToggleButtonWidget.prototype.onAction = function () {
this.setValue( !this.value );
};
/**
* @inheritdoc
*/
OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
value = !!value;
if ( value !== this.value ) {
// Might be called from parent constructor before ButtonElement constructor
if ( this.$button ) {
this.$button.attr( 'aria-pressed', value.toString() );
}
this.setActive( value );
}
// Parent method
OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
return this;
};
/**
* @inheritdoc
*/
OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
if ( this.$button ) {
this.$button.removeAttr( 'aria-pressed' );
}
OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
this.$button.attr( 'aria-pressed', this.value.toString() );
};
/**
* ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
* value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
* visually by a slider in the leftmost position.
*
* @example
* // Toggle switches in the 'off' and 'on' position.
* var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
* var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
* value: true
* } );
*
* // Create a FieldsetLayout to layout and label switches
* var fieldset = new OO.ui.FieldsetLayout( {
* label: 'Toggle switches'
* } );
* fieldset.addItems( [
* new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
* new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
* ] );
* $( 'body' ).append( fieldset.$element );
*
* @class
* @extends OO.ui.ToggleWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
* By default, the toggle switch is in the 'off' position.
*/
OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
// Parent constructor
OO.ui.ToggleSwitchWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Properties
this.dragging = false;
this.dragStart = null;
this.sliding = false;
this.$glow = $( '<span>' );
this.$grip = $( '<span>' );
// Events
this.$element.on( {
click: this.onClick.bind( this ),
keypress: this.onKeyPress.bind( this )
} );
// Initialization
this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
this.$element
.addClass( 'oo-ui-toggleSwitchWidget' )
.attr( 'role', 'checkbox' )
.append( this.$glow, this.$grip );
};
/* Setup */
OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Handle mouse click events.
*
* @private
* @param {jQuery.Event} e Mouse click event
*/
OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
this.setValue( !this.value );
}
return false;
};
/**
* Handle key press events.
*
* @private
* @param {jQuery.Event} e Key press event
*/
OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
this.setValue( !this.value );
return false;
}
};
/**
* OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
* Controls include moving items up and down, removing items, and adding different kinds of items.
*
* **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
* @mixins OO.ui.mixin.IconElement
*
* @constructor
* @param {OO.ui.OutlineSelectWidget} outline Outline to control
* @param {Object} [config] Configuration options
* @cfg {Object} [abilities] List of abilties
* @cfg {boolean} [abilities.move=true] Allow moving movable items
* @cfg {boolean} [abilities.remove=true] Allow removing removable items
*/
OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( outline ) && config === undefined ) {
config = outline;
outline = config.outline;
}
// Configuration initialization
config = $.extend( { icon: 'add' }, config );
// Parent constructor
OO.ui.OutlineControlsWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
OO.ui.mixin.IconElement.call( this, config );
// Properties
this.outline = outline;
this.$movers = $( '<div>' );
this.upButton = new OO.ui.ButtonWidget( {
framed: false,
icon: 'collapse',
title: OO.ui.msg( 'ooui-outline-control-move-up' )
} );
this.downButton = new OO.ui.ButtonWidget( {
framed: false,
icon: 'expand',
title: OO.ui.msg( 'ooui-outline-control-move-down' )
} );
this.removeButton = new OO.ui.ButtonWidget( {
framed: false,
icon: 'remove',
title: OO.ui.msg( 'ooui-outline-control-remove' )
} );
this.abilities = { move: true, remove: true };
// Events
outline.connect( this, {
select: 'onOutlineChange',
add: 'onOutlineChange',
remove: 'onOutlineChange'
} );
this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
// Initialization
this.$element.addClass( 'oo-ui-outlineControlsWidget' );
this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
this.$movers
.addClass( 'oo-ui-outlineControlsWidget-movers' )
.append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
this.$element.append( this.$icon, this.$group, this.$movers );
this.setAbilities( config.abilities || {} );
};
/* Setup */
OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
/* Events */
/**
* @event move
* @param {number} places Number of places to move
*/
/**
* @event remove
*/
/* Methods */
/**
* Set abilities.
*
* @param {Object} abilities List of abilties
* @param {boolean} [abilities.move] Allow moving movable items
* @param {boolean} [abilities.remove] Allow removing removable items
*/
OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
var ability;
for ( ability in this.abilities ) {
if ( abilities[ ability ] !== undefined ) {
this.abilities[ ability ] = !!abilities[ ability ];
}
}
this.onOutlineChange();
};
/**
* Handle outline change events.
*
* @private
*/
OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
var i, len, firstMovable, lastMovable,
items = this.outline.getItems(),
selectedItem = this.outline.getSelectedItem(),
movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
if ( movable ) {
i = -1;
len = items.length;
while ( ++i < len ) {
if ( items[ i ].isMovable() ) {
firstMovable = items[ i ];
break;
}
}
i = len;
while ( i-- ) {
if ( items[ i ].isMovable() ) {
lastMovable = items[ i ];
break;
}
}
}
this.upButton.setDisabled( !movable || selectedItem === firstMovable );
this.downButton.setDisabled( !movable || selectedItem === lastMovable );
this.removeButton.setDisabled( !removable );
};
/**
* OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
*
* Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
* {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
* for an example.
*
* @class
* @extends OO.ui.DecoratedOptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {number} [level] Indentation level
* @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
*/
OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.OutlineOptionWidget.parent.call( this, config );
// Properties
this.level = 0;
this.movable = !!config.movable;
this.removable = !!config.removable;
// Initialization
this.$element.addClass( 'oo-ui-outlineOptionWidget' );
this.setLevel( config.level );
};
/* Setup */
OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.OutlineOptionWidget.static.highlightable = true;
/**
* @static
* @inheritdoc
*/
OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
/**
* @static
* @inheritable
* @property {string}
*/
OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
/**
* @static
* @inheritable
* @property {number}
*/
OO.ui.OutlineOptionWidget.static.levels = 3;
/* Methods */
/**
* Check if item is movable.
*
* Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
*
* @return {boolean} Item is movable
*/
OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
return this.movable;
};
/**
* Check if item is removable.
*
* Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
*
* @return {boolean} Item is removable
*/
OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
return this.removable;
};
/**
* Get indentation level.
*
* @return {number} Indentation level
*/
OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
return this.level;
};
/**
* @inheritdoc
*/
OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
if ( this.pressed ) {
this.setFlags( { progressive: true } );
} else if ( !this.selected ) {
this.setFlags( { progressive: false } );
}
return this;
};
/**
* Set movability.
*
* Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
*
* @param {boolean} movable Item is movable
* @chainable
*/
OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
this.movable = !!movable;
this.updateThemeClasses();
return this;
};
/**
* Set removability.
*
* Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
*
* @param {boolean} removable Item is removable
* @chainable
*/
OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
this.removable = !!removable;
this.updateThemeClasses();
return this;
};
/**
* @inheritdoc
*/
OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
if ( this.selected ) {
this.setFlags( { progressive: true } );
} else {
this.setFlags( { progressive: false } );
}
return this;
};
/**
* Set indentation level.
*
* @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
* @chainable
*/
OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
var levels = this.constructor.static.levels,
levelClass = this.constructor.static.levelClass,
i = levels;
this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
while ( i-- ) {
if ( this.level === i ) {
this.$element.addClass( levelClass + i );
} else {
this.$element.removeClass( levelClass + i );
}
}
this.updateThemeClasses();
return this;
};
/**
* OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
* A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
*
* **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
// Parent constructor
OO.ui.OutlineSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.$element.on( {
focus: this.bindKeyDownListener.bind( this ),
blur: this.unbindKeyDownListener.bind( this )
} );
// Initialization
this.$element.addClass( 'oo-ui-outlineSelectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
/**
* ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
* can be selected and configured with data. The class is
* used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
* [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
*
* @class
* @extends OO.ui.OptionWidget
* @mixins OO.ui.mixin.ButtonElement
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ButtonOptionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ButtonElement.call( this, config );
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
// Initialization
this.$element.addClass( 'oo-ui-buttonOptionWidget' );
this.$button.append( this.$icon, this.$label, this.$indicator );
this.$element.append( this.$button );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
/* Static Properties */
/**
* Allow button mouse down events to pass through so they can be handled by the parent select widget
*
* @static
* @inheritdoc
*/
OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
/**
* @static
* @inheritdoc
*/
OO.ui.ButtonOptionWidget.static.highlightable = false;
/* Methods */
/**
* @inheritdoc
*/
OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
if ( this.constructor.static.selectable ) {
this.setActive( state );
}
return this;
};
/**
* ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
* button options and is used together with
* OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
* highlighting, choosing, and selecting mutually exclusive options. Please see
* the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* @example
* // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
* var option1 = new OO.ui.ButtonOptionWidget( {
* data: 1,
* label: 'Option 1',
* title: 'Button option 1'
* } );
*
* var option2 = new OO.ui.ButtonOptionWidget( {
* data: 2,
* label: 'Option 2',
* title: 'Button option 2'
* } );
*
* var option3 = new OO.ui.ButtonOptionWidget( {
* data: 3,
* label: 'Option 3',
* title: 'Button option 3'
* } );
*
* var buttonSelect=new OO.ui.ButtonSelectWidget( {
* items: [ option1, option2, option3 ]
* } );
* $( 'body' ).append( buttonSelect.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
// Parent constructor
OO.ui.ButtonSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.$element.on( {
focus: this.bindKeyDownListener.bind( this ),
blur: this.unbindKeyDownListener.bind( this )
} );
// Initialization
this.$element.addClass( 'oo-ui-buttonSelectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
/**
* TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
*
* Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
* {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
* for an example.
*
* @class
* @extends OO.ui.OptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.TabOptionWidget.parent.call( this, config );
// Initialization
this.$element.addClass( 'oo-ui-tabOptionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.TabOptionWidget.static.highlightable = false;
/**
* TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
*
* **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
*
* @class
* @extends OO.ui.SelectWidget
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
// Parent constructor
OO.ui.TabSelectWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.$element.on( {
focus: this.bindKeyDownListener.bind( this ),
blur: this.unbindKeyDownListener.bind( this )
} );
// Initialization
this.$element.addClass( 'oo-ui-tabSelectWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
/**
* CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
* CapsuleMultiselectWidget} to display the selected items.
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.ItemWidget
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.CapsuleItemWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.ItemWidget.call( this );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, config );
// Events
this.closeButton = new OO.ui.ButtonWidget( {
framed: false,
indicator: 'clear',
tabIndex: -1
} ).on( 'click', this.onCloseClick.bind( this ) );
this.on( 'disable', function ( disabled ) {
this.closeButton.setDisabled( disabled );
}.bind( this ) );
// Initialization
this.$element
.on( {
click: this.onClick.bind( this ),
keydown: this.onKeyDown.bind( this )
} )
.addClass( 'oo-ui-capsuleItemWidget' )
.append( this.$label, this.closeButton.$element );
};
/* Setup */
OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* Handle close icon clicks
*/
OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
var element = this.getElementGroup();
if ( element && $.isFunction( element.removeItems ) ) {
element.removeItems( [ this ] );
element.focus();
}
};
/**
* Handle click event for the entire capsule
*/
OO.ui.CapsuleItemWidget.prototype.onClick = function () {
var element = this.getElementGroup();
if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
element.editItem( this );
}
};
/**
* Handle keyDown event for the entire capsule
*
* @param {jQuery.Event} e Key down event
*/
OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
var element = this.getElementGroup();
if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
element.removeItems( [ this ] );
element.focus();
return false;
} else if ( e.keyCode === OO.ui.Keys.ENTER ) {
element.editItem( this );
return false;
} else if ( e.keyCode === OO.ui.Keys.LEFT ) {
element.getPreviousItem( this ).focus();
} else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
element.getNextItem( this ).focus();
}
};
/**
* Focuses the capsule
*/
OO.ui.CapsuleItemWidget.prototype.focus = function () {
this.$element.focus();
};
/**
* CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
* that allows for selecting multiple values.
*
* For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example: A CapsuleMultiselectWidget.
* var capsule = new OO.ui.CapsuleMultiselectWidget( {
* label: 'CapsuleMultiselectWidget',
* selected: [ 'Option 1', 'Option 3' ],
* menu: {
* items: [
* new OO.ui.MenuOptionWidget( {
* data: 'Option 1',
* label: 'Option One'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 2',
* label: 'Option Two'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 3',
* label: 'Option Three'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 4',
* label: 'Option Four'
* } ),
* new OO.ui.MenuOptionWidget( {
* data: 'Option 5',
* label: 'Option Five'
* } )
* ]
* }
* } );
* $( 'body' ).append( capsule.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
* @mixins OO.ui.mixin.PopupElement
* @mixins OO.ui.mixin.TabIndexedElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.IconElement
* @uses OO.ui.CapsuleItemWidget
* @uses OO.ui.FloatingMenuSelectWidget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [placeholder] Placeholder text
* @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
* @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
* @cfg {Object} [menu] (required) Configuration options to pass to the
* {@link OO.ui.MenuSelectWidget menu select widget}.
* @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
* If specified, this popup will be shown instead of the menu (but the menu
* will still be used for item labels and allowArbitrary=false). The widgets
* in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
* @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
* This configuration is useful in cases where the expanded menu is larger than
* its containing `<div>`. The specified overlay layer is usually on top of
* the containing `<div>` and has a larger area. By default, the menu uses
* relative positioning.
*/
OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
var $tabFocus;
// Parent constructor
OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
// Configuration initialization
config = $.extend( {
allowArbitrary: false,
allowDuplicates: false,
$overlay: this.$element
}, config );
// Properties (must be set before mixin constructor calls)
this.$handle = $( '<div>' );
this.$input = config.popup ? null : $( '<input>' );
if ( config.placeholder !== undefined && config.placeholder !== '' ) {
this.$input.attr( 'placeholder', config.placeholder );
}
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
if ( config.popup ) {
config.popup = $.extend( {}, config.popup, {
align: 'forwards',
anchor: false
} );
OO.ui.mixin.PopupElement.call( this, $.extend( true, {}, config, {
popup: {
$floatableContainer: this.$element
}
} ) );
$tabFocus = $( '<span>' );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
} else {
this.popup = null;
$tabFocus = null;
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
}
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.IconElement.call( this, config );
// Properties
this.$content = $( '<div>' );
this.allowArbitrary = config.allowArbitrary;
this.allowDuplicates = config.allowDuplicates;
this.$overlay = config.$overlay;
this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
{
widget: this,
$input: this.$input,
$container: this.$element,
filterFromInput: true,
disabled: this.isDisabled()
},
config.menu
) );
// Events
if ( this.popup ) {
$tabFocus.on( {
focus: this.focus.bind( this )
} );
this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
if ( this.popup.$autoCloseIgnore ) {
this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
}
this.popup.connect( this, {
toggle: function ( visible ) {
$tabFocus.toggle( !visible );
}
} );
} else {
this.$input.on( {
focus: this.onInputFocus.bind( this ),
blur: this.onInputBlur.bind( this ),
'propertychange change click mouseup keydown keyup input cut paste select focus':
OO.ui.debounce( this.updateInputSize.bind( this ) ),
keydown: this.onKeyDown.bind( this ),
keypress: this.onKeyPress.bind( this )
} );
}
this.menu.connect( this, {
choose: 'onMenuChoose',
toggle: 'onMenuToggle',
add: 'onMenuItemsChange',
remove: 'onMenuItemsChange'
} );
this.$handle.on( {
mousedown: this.onMouseDown.bind( this )
} );
// Initialization
if ( this.$input ) {
this.$input.prop( 'disabled', this.isDisabled() );
this.$input.attr( {
role: 'combobox',
'aria-autocomplete': 'list'
} );
}
if ( config.data ) {
this.setItemsFromData( config.data );
}
this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
.append( this.$group );
this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
.append( this.$indicator, this.$icon, this.$content );
this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
.append( this.$handle );
if ( this.popup ) {
this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
this.$content.append( $tabFocus );
this.$overlay.append( this.popup.$element );
} else {
this.$content.append( this.$input );
this.$overlay.append( this.menu.$element );
}
if ( $tabFocus ) {
$tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
}
// Input size needs to be calculated after everything else is rendered
setTimeout( function () {
if ( this.$input ) {
this.updateInputSize();
}
}.bind( this ) );
this.onMenuItemsChange();
};
/* Setup */
OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
/* Static Properties */
OO.ui.CapsuleMultiselectWidget.static.supportsSimpleLabel = true;
/* Events */
/**
* @event change
*
* A change event is emitted when the set of selected items changes.
*
* @param {Mixed[]} datas Data of the now-selected items
*/
/**
* @event resize
*
* A resize event is emitted when the widget's dimensions change to accomodate newly added items or
* current user input.
*/
/* Methods */
/**
* Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
* May return `null` if the given label and data are not valid.
*
* @protected
* @param {Mixed} data Custom data of any type.
* @param {string} label The label text.
* @return {OO.ui.CapsuleItemWidget|null}
*/
OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
if ( label === '' ) {
return null;
}
return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
};
/**
* Get the widget's input's id, or generate one, if it has an input.
*
* @return {string}
*/
OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
var id;
if ( !this.$input ) {
return false;
}
id = this.$input.attr( 'id' );
if ( id === undefined ) {
id = OO.ui.generateElementId();
this.$input.attr( 'id', id );
}
return id;
};
/**
* Get the data of the items in the capsule
*
* @return {Mixed[]}
*/
OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
return this.getItems().map( function ( item ) {
return item.data;
} );
};
/**
* Set the items in the capsule by providing data
*
* @chainable
* @param {Mixed[]} datas
* @return {OO.ui.CapsuleMultiselectWidget}
*/
OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
var widget = this,
menu = this.menu,
items = this.getItems();
$.each( datas, function ( i, data ) {
var j, label,
item = menu.getItemFromData( data );
if ( item ) {
label = item.label;
} else if ( widget.allowArbitrary ) {
label = String( data );
} else {
return;
}
item = null;
for ( j = 0; j < items.length; j++ ) {
if ( items[ j ].data === data && items[ j ].label === label ) {
item = items[ j ];
items.splice( j, 1 );
break;
}
}
if ( !item ) {
item = widget.createItemWidget( data, label );
}
if ( item ) {
widget.addItems( [ item ], i );
}
} );
if ( items.length ) {
widget.removeItems( items );
}
return this;
};
/**
* Add items to the capsule by providing their data
*
* @chainable
* @param {Mixed[]} datas
* @return {OO.ui.CapsuleMultiselectWidget}
*/
OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
var widget = this,
menu = this.menu,
items = [];
$.each( datas, function ( i, data ) {
var item;
if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
item = menu.getItemFromData( data );
if ( item ) {
item = widget.createItemWidget( data, item.label );
} else if ( widget.allowArbitrary ) {
item = widget.createItemWidget( data, String( data ) );
}
if ( item ) {
items.push( item );
}
}
} );
if ( items.length ) {
this.addItems( items );
}
return this;
};
/**
* Add items to the capsule by providing a label
*
* @param {string} label
* @return {boolean} Whether the item was added or not
*/
OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
var item, items;
item = this.menu.getItemFromLabel( label, true );
if ( item ) {
this.addItemsFromData( [ item.data ] );
return true;
} else if ( this.allowArbitrary ) {
items = this.getItems();
this.addItemsFromData( [ label ] );
return !OO.compare( this.getItems(), items );
}
return false;
};
/**
* Remove items by data
*
* @chainable
* @param {Mixed[]} datas
* @return {OO.ui.CapsuleMultiselectWidget}
*/
OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
var widget = this,
items = [];
$.each( datas, function ( i, data ) {
var item = widget.getItemFromData( data );
if ( item ) {
items.push( item );
}
} );
if ( items.length ) {
this.removeItems( items );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
var same, i, l,
oldItems = this.items.slice();
OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
if ( this.items.length !== oldItems.length ) {
same = false;
} else {
same = true;
for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
same = same && this.items[ i ] === oldItems[ i ];
}
}
if ( !same ) {
this.emit( 'change', this.getItemsData() );
this.updateIfHeightChanged();
}
return this;
};
/**
* Removes the item from the list and copies its label to `this.$input`.
*
* @param {Object} item
*/
OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
this.addItemFromLabel( this.$input.val() );
this.clearInput();
this.$input.val( item.label );
this.updateInputSize();
this.focus();
this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
this.removeItems( [ item ] );
};
/**
* @inheritdoc
*/
OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
var same, i, l,
oldItems = this.items.slice();
OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
if ( this.items.length !== oldItems.length ) {
same = false;
} else {
same = true;
for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
same = same && this.items[ i ] === oldItems[ i ];
}
}
if ( !same ) {
this.emit( 'change', this.getItemsData() );
this.updateIfHeightChanged();
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
if ( this.items.length ) {
OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
this.emit( 'change', this.getItemsData() );
this.updateIfHeightChanged();
}
return this;
};
/**
* Given an item, returns the item after it. If its the last item,
* returns `this.$input`. If no item is passed, returns the very first
* item.
*
* @param {OO.ui.CapsuleItemWidget} [item]
* @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
*/
OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
var itemIndex;
if ( item === undefined ) {
return this.items[ 0 ];
}
itemIndex = this.items.indexOf( item );
if ( itemIndex < 0 ) { // Item not in list
return false;
} else if ( itemIndex === this.items.length - 1 ) { // Last item
return this.$input;
} else {
return this.items[ itemIndex + 1 ];
}
};
/**
* Given an item, returns the item before it. If its the first item,
* returns `this.$input`. If no item is passed, returns the very last
* item.
*
* @param {OO.ui.CapsuleItemWidget} [item]
* @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
*/
OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
var itemIndex;
if ( item === undefined ) {
return this.items[ this.items.length - 1 ];
}
itemIndex = this.items.indexOf( item );
if ( itemIndex < 0 ) { // Item not in list
return false;
} else if ( itemIndex === 0 ) { // First item
return this.$input;
} else {
return this.items[ itemIndex - 1 ];
}
};
/**
* Get the capsule widget's menu.
*
* @return {OO.ui.MenuSelectWidget} Menu widget
*/
OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
return this.menu;
};
/**
* Handle focus events
*
* @private
* @param {jQuery.Event} event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
if ( !this.isDisabled() ) {
this.menu.toggle( true );
}
};
/**
* Handle blur events
*
* @private
* @param {jQuery.Event} event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
this.addItemFromLabel( this.$input.val() );
this.clearInput();
};
/**
* Handles popup focus out events.
*
* @private
* @param {jQuery.Event} e Focus out event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
var widget = this.popup;
setTimeout( function () {
if (
widget.isVisible() &&
!OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
) {
widget.toggle( false );
}
} );
};
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
if ( e.which === OO.ui.MouseButtons.LEFT ) {
this.focus();
return false;
} else {
this.updateInputSize();
}
};
/**
* Handle key press events.
*
* @private
* @param {jQuery.Event} e Key press event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
if ( !this.isDisabled() ) {
if ( e.which === OO.ui.Keys.ESCAPE ) {
this.clearInput();
return false;
}
if ( !this.popup ) {
this.menu.toggle( true );
if ( e.which === OO.ui.Keys.ENTER ) {
if ( this.addItemFromLabel( this.$input.val() ) ) {
this.clearInput();
}
return false;
}
// Make sure the input gets resized.
setTimeout( this.updateInputSize.bind( this ), 0 );
}
}
};
/**
* Handle key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
if (
!this.isDisabled() &&
this.$input.val() === '' &&
this.items.length
) {
// 'keypress' event is not triggered for Backspace
if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
if ( e.metaKey || e.ctrlKey ) {
this.removeItems( this.items.slice( -1 ) );
} else {
this.editItem( this.items[ this.items.length - 1 ] );
}
return false;
} else if ( e.keyCode === OO.ui.Keys.LEFT ) {
this.getPreviousItem().focus();
} else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
this.getNextItem().focus();
}
}
};
/**
* Update the dimensions of the text input field to encompass all available area.
*
* @private
* @param {jQuery.Event} e Event of some sort
*/
OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
var $lastItem, direction, contentWidth, currentWidth, bestWidth;
if ( this.$input && !this.isDisabled() ) {
this.$input.css( 'width', '1em' );
$lastItem = this.$group.children().last();
direction = OO.ui.Element.static.getDir( this.$handle );
// Get the width of the input with the placeholder text as
// the value and save it so that we don't keep recalculating
if (
this.contentWidthWithPlaceholder === undefined &&
this.$input.val() === '' &&
this.$input.attr( 'placeholder' ) !== undefined
) {
this.$input.val( this.$input.attr( 'placeholder' ) );
this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
this.$input.val( '' );
}
// Always keep the input wide enough for the placeholder text
contentWidth = Math.max(
this.$input[ 0 ].scrollWidth,
// undefined arguments in Math.max lead to NaN
( this.contentWidthWithPlaceholder === undefined ) ?
0 : this.contentWidthWithPlaceholder
);
currentWidth = this.$input.width();
if ( contentWidth < currentWidth ) {
// All is fine, don't perform expensive calculations
return;
}
if ( $lastItem.length === 0 ) {
bestWidth = this.$content.innerWidth();
} else {
bestWidth = direction === 'ltr' ?
this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
$lastItem.position().left;
}
// Some safety margin for sanity, because I *really* don't feel like finding out where the few
// pixels this is off by are coming from.
bestWidth -= 10;
if ( contentWidth > bestWidth ) {
// This will result in the input getting shifted to the next line
bestWidth = this.$content.innerWidth() - 10;
}
this.$input.width( Math.floor( bestWidth ) );
this.updateIfHeightChanged();
}
};
/**
* Determine if widget height changed, and if so, update menu position and emit 'resize' event.
*
* @private
*/
OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
var height = this.$element.height();
if ( height !== this.height ) {
this.height = height;
this.menu.position();
this.emit( 'resize' );
}
};
/**
* Handle menu choose events.
*
* @private
* @param {OO.ui.OptionWidget} item Chosen item
*/
OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
if ( item && item.isVisible() ) {
this.addItemsFromData( [ item.getData() ] );
this.clearInput();
}
};
/**
* Handle menu toggle events.
*
* @private
* @param {boolean} isVisible Menu toggle event
*/
OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
};
/**
* Handle menu item change events.
*
* @private
*/
OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
this.setItemsFromData( this.getItemsData() );
this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
};
/**
* Clear the input field
*
* @private
*/
OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
if ( this.$input ) {
this.$input.val( '' );
this.updateInputSize();
}
if ( this.popup ) {
this.popup.toggle( false );
}
this.menu.toggle( false );
this.menu.selectItem();
this.menu.highlightItem();
};
/**
* @inheritdoc
*/
OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
var i, len;
// Parent method
OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.$input ) {
this.$input.prop( 'disabled', this.isDisabled() );
}
if ( this.menu ) {
this.menu.setDisabled( this.isDisabled() );
}
if ( this.popup ) {
this.popup.setDisabled( this.isDisabled() );
}
if ( this.items ) {
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].updateDisabled();
}
}
return this;
};
/**
* Focus the widget
*
* @chainable
* @return {OO.ui.CapsuleMultiselectWidget}
*/
OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
if ( !this.isDisabled() ) {
if ( this.popup ) {
this.popup.setSize( this.$handle.outerWidth() );
this.popup.toggle( true );
OO.ui.findFocusable( this.popup.$element ).focus();
} else {
this.updateInputSize();
this.menu.toggle( true );
this.$input.focus();
}
}
return this;
};
/**
* The old name for the CapsuleMultiselectWidget widget, provided for backwards-compatibility.
*
* @class
* @extends OO.ui.CapsuleMultiselectWidget
*
* @constructor
* @deprecated since 0.17.3; use OO.ui.CapsuleMultiselectWidget instead
*/
OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget() {
OO.ui.warnDeprecation( 'CapsuleMultiSelectWidget is deprecated. Use the CapsuleMultiselectWidget instead.' );
// Parent constructor
OO.ui.CapsuleMultiSelectWidget.parent.apply( this, arguments );
};
OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.CapsuleMultiselectWidget );
/**
* SelectFileWidgets allow for selecting files, using the HTML5 File API. These
* widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
* OO.ui.mixin.IndicatorElement indicators}.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
*
* @example
* // Example of a file select widget
* var selectFile = new OO.ui.SelectFileWidget();
* $( 'body' ).append( selectFile.$element );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.PendingElement
* @mixins OO.ui.mixin.LabelElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
* @cfg {string} [placeholder] Text to display when no file is selected.
* @cfg {string} [notsupported] Text to display when file support is missing in the browser.
* @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
* @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
* @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
* preview (for performance)
*/
OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
var dragHandler;
// Configuration initialization
config = $.extend( {
accept: null,
placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
droppable: true,
showDropTarget: false,
thumbnailSizeLimit: 20
}, config );
// Parent constructor
OO.ui.SelectFileWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
OO.ui.mixin.LabelElement.call( this, config );
// Properties
this.$info = $( '<span>' );
this.showDropTarget = config.showDropTarget;
this.thumbnailSizeLimit = config.thumbnailSizeLimit;
this.isSupported = this.constructor.static.isSupported();
this.currentFile = null;
if ( Array.isArray( config.accept ) ) {
this.accept = config.accept;
} else {
this.accept = null;
}
this.placeholder = config.placeholder;
this.notsupported = config.notsupported;
this.onFileSelectedHandler = this.onFileSelected.bind( this );
this.selectButton = new OO.ui.ButtonWidget( {
classes: [ 'oo-ui-selectFileWidget-selectButton' ],
label: OO.ui.msg( 'ooui-selectfile-button-select' ),
disabled: this.disabled || !this.isSupported
} );
this.clearButton = new OO.ui.ButtonWidget( {
classes: [ 'oo-ui-selectFileWidget-clearButton' ],
framed: false,
icon: 'close',
disabled: this.disabled
} );
// Events
this.selectButton.$button.on( {
keypress: this.onKeyPress.bind( this )
} );
this.clearButton.connect( this, {
click: 'onClearClick'
} );
if ( config.droppable ) {
dragHandler = this.onDragEnterOrOver.bind( this );
this.$element.on( {
dragenter: dragHandler,
dragover: dragHandler,
dragleave: this.onDragLeave.bind( this ),
drop: this.onDrop.bind( this )
} );
}
// Initialization
this.addInput();
this.$label.addClass( 'oo-ui-selectFileWidget-label' );
this.$info
.addClass( 'oo-ui-selectFileWidget-info' )
.append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
if ( config.droppable && config.showDropTarget ) {
this.selectButton.setIcon( 'upload' );
this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
this.setPendingElement( this.$thumbnail );
this.$element
.addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
.on( {
click: this.onDropTargetClick.bind( this )
} )
.append(
this.$thumbnail,
this.$info,
this.selectButton.$element,
$( '<span>' )
.addClass( 'oo-ui-selectFileWidget-dropLabel' )
.text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
);
} else {
this.$element
.addClass( 'oo-ui-selectFileWidget' )
.append( this.$info, this.selectButton.$element );
}
this.updateUI();
};
/* Setup */
OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
/* Static Properties */
/**
* Check if this widget is supported
*
* @static
* @return {boolean}
*/
OO.ui.SelectFileWidget.static.isSupported = function () {
var $input;
if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
$input = $( '<input>' ).attr( 'type', 'file' );
OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
}
return OO.ui.SelectFileWidget.static.isSupportedCache;
};
OO.ui.SelectFileWidget.static.isSupportedCache = null;
/* Events */
/**
* @event change
*
* A change event is emitted when the on/off state of the toggle changes.
*
* @param {File|null} value New value
*/
/* Methods */
/**
* Get the current value of the field
*
* @return {File|null}
*/
OO.ui.SelectFileWidget.prototype.getValue = function () {
return this.currentFile;
};
/**
* Set the current value of the field
*
* @param {File|null} file File to select
*/
OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
if ( this.currentFile !== file ) {
this.currentFile = file;
this.updateUI();
this.emit( 'change', this.currentFile );
}
};
/**
* Focus the widget.
*
* Focusses the select file button.
*
* @chainable
*/
OO.ui.SelectFileWidget.prototype.focus = function () {
this.selectButton.$button[ 0 ].focus();
return this;
};
/**
* Update the user interface when a file is selected or unselected
*
* @protected
*/
OO.ui.SelectFileWidget.prototype.updateUI = function () {
var $label;
if ( !this.isSupported ) {
this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
this.setLabel( this.notsupported );
} else {
this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
if ( this.currentFile ) {
this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
$label = $( [] );
$label = $label.add(
$( '<span>' )
.addClass( 'oo-ui-selectFileWidget-fileName' )
.text( this.currentFile.name )
);
this.setLabel( $label );
if ( this.showDropTarget ) {
this.pushPending();
this.loadAndGetImageUrl().done( function ( url ) {
this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
}.bind( this ) ).fail( function () {
this.$thumbnail.append(
new OO.ui.IconWidget( {
icon: 'attachment',
classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
} ).$element
);
}.bind( this ) ).always( function () {
this.popPending();
}.bind( this ) );
this.$element.off( 'click' );
}
} else {
if ( this.showDropTarget ) {
this.$element.off( 'click' );
this.$element.on( {
click: this.onDropTargetClick.bind( this )
} );
this.$thumbnail
.empty()
.css( 'background-image', '' );
}
this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
this.setLabel( this.placeholder );
}
}
};
/**
* If the selected file is an image, get its URL and load it.
*
* @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
*/
OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
var deferred = $.Deferred(),
file = this.currentFile,
reader = new FileReader();
if (
file &&
( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
file.size < this.thumbnailSizeLimit * 1024 * 1024
) {
reader.onload = function ( event ) {
var img = document.createElement( 'img' );
img.addEventListener( 'load', function () {
if (
img.naturalWidth === 0 ||
img.naturalHeight === 0 ||
img.complete === false
) {
deferred.reject();
} else {
deferred.resolve( event.target.result );
}
} );
img.src = event.target.result;
};
reader.readAsDataURL( file );
} else {
deferred.reject();
}
return deferred.promise();
};
/**
* Add the input to the widget
*
* @private
*/
OO.ui.SelectFileWidget.prototype.addInput = function () {
if ( this.$input ) {
this.$input.remove();
}
if ( !this.isSupported ) {
this.$input = null;
return;
}
this.$input = $( '<input>' ).attr( 'type', 'file' );
this.$input.on( 'change', this.onFileSelectedHandler );
this.$input.on( 'click', function ( e ) {
// Prevents dropTarget to get clicked which calls
// a click on this input
e.stopPropagation();
} );
this.$input.attr( {
tabindex: -1
} );
if ( this.accept ) {
this.$input.attr( 'accept', this.accept.join( ', ' ) );
}
this.selectButton.$button.append( this.$input );
};
/**
* Determine if we should accept this file
*
* @private
* @param {string} mimeType File MIME type
* @return {boolean}
*/
OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
var i, mimeTest;
if ( !this.accept || !mimeType ) {
return true;
}
for ( i = 0; i < this.accept.length; i++ ) {
mimeTest = this.accept[ i ];
if ( mimeTest === mimeType ) {
return true;
} else if ( mimeTest.substr( -2 ) === '/*' ) {
mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
return true;
}
}
}
return false;
};
/**
* Handle file selection from the input
*
* @private
* @param {jQuery.Event} e
*/
OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
var file = OO.getProp( e.target, 'files', 0 ) || null;
if ( file && !this.isAllowedType( file.type ) ) {
file = null;
}
this.setValue( file );
this.addInput();
};
/**
* Handle clear button click events.
*
* @private
*/
OO.ui.SelectFileWidget.prototype.onClearClick = function () {
this.setValue( null );
return false;
};
/**
* Handle key press events.
*
* @private
* @param {jQuery.Event} e Key press event
*/
OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
if ( this.isSupported && !this.isDisabled() && this.$input &&
( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
this.$input.click();
return false;
}
};
/**
* Handle drop target click events.
*
* @private
* @param {jQuery.Event} e Key press event
*/
OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
if ( this.isSupported && !this.isDisabled() && this.$input ) {
this.$input.click();
return false;
}
};
/**
* Handle drag enter and over events
*
* @private
* @param {jQuery.Event} e Drag event
*/
OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
var itemOrFile,
droppableFile = false,
dt = e.originalEvent.dataTransfer;
e.preventDefault();
e.stopPropagation();
if ( this.isDisabled() || !this.isSupported ) {
this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
dt.dropEffect = 'none';
return false;
}
// DataTransferItem and File both have a type property, but in Chrome files
// have no information at this point.
itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
if ( itemOrFile ) {
if ( this.isAllowedType( itemOrFile.type ) ) {
droppableFile = true;
}
// dt.types is Array-like, but not an Array
} else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
// File information is not available at this point for security so just assume
// it is acceptable for now.
// https://bugzilla.mozilla.org/show_bug.cgi?id=640534
droppableFile = true;
}
this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
if ( !droppableFile ) {
dt.dropEffect = 'none';
}
return false;
};
/**
* Handle drag leave events
*
* @private
* @param {jQuery.Event} e Drag event
*/
OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
};
/**
* Handle drop events
*
* @private
* @param {jQuery.Event} e Drop event
*/
OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
var file = null,
dt = e.originalEvent.dataTransfer;
e.preventDefault();
e.stopPropagation();
this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
if ( this.isDisabled() || !this.isSupported ) {
return false;
}
file = OO.getProp( dt, 'files', 0 );
if ( file && !this.isAllowedType( file.type ) ) {
file = null;
}
if ( file ) {
this.setValue( file );
}
return false;
};
/**
* @inheritdoc
*/
OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.selectButton ) {
this.selectButton.setDisabled( disabled );
}
if ( this.clearButton ) {
this.clearButton.setDisabled( disabled );
}
return this;
};
/**
* SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
* and a menu of search results, which is displayed beneath the query
* field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
* Users can choose an item from the menu or type a query into the text field to search for a matching result item.
* In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
*
* Each time the query is changed, the search result menu is cleared and repopulated. Please see
* the [OOjs UI demos][1] for an example.
*
* [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
*
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string|jQuery} [placeholder] Placeholder text for query input
* @cfg {string} [value] Initial query value
*/
OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.SearchWidget.parent.call( this, config );
// Properties
this.query = new OO.ui.TextInputWidget( {
icon: 'search',
placeholder: config.placeholder,
value: config.value
} );
this.results = new OO.ui.SelectWidget();
this.$query = $( '<div>' );
this.$results = $( '<div>' );
// Events
this.query.connect( this, {
change: 'onQueryChange',
enter: 'onQueryEnter'
} );
this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
// Initialization
this.$query
.addClass( 'oo-ui-searchWidget-query' )
.append( this.query.$element );
this.$results
.addClass( 'oo-ui-searchWidget-results' )
.append( this.results.$element );
this.$element
.addClass( 'oo-ui-searchWidget' )
.append( this.$results, this.$query );
};
/* Setup */
OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
/* Methods */
/**
* Handle query key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
var highlightedItem, nextItem,
dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
if ( dir ) {
highlightedItem = this.results.getHighlightedItem();
if ( !highlightedItem ) {
highlightedItem = this.results.getSelectedItem();
}
nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
this.results.highlightItem( nextItem );
nextItem.scrollElementIntoView();
}
};
/**
* Handle select widget select events.
*
* Clears existing results. Subclasses should repopulate items according to new query.
*
* @private
* @param {string} value New value
*/
OO.ui.SearchWidget.prototype.onQueryChange = function () {
// Reset
this.results.clearItems();
};
/**
* Handle select widget enter key events.
*
* Chooses highlighted item.
*
* @private
* @param {string} value New value
*/
OO.ui.SearchWidget.prototype.onQueryEnter = function () {
var highlightedItem = this.results.getHighlightedItem();
if ( highlightedItem ) {
this.results.chooseItem( highlightedItem );
}
};
/**
* Get the query input.
*
* @return {OO.ui.TextInputWidget} Query input
*/
OO.ui.SearchWidget.prototype.getQuery = function () {
return this.query;
};
/**
* Get the search results menu.
*
* @return {OO.ui.SelectWidget} Menu of search results
*/
OO.ui.SearchWidget.prototype.getResults = function () {
return this.results;
};
/**
* NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
* can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
* (to adjust the value in increments) to allow the user to enter a number.
*
* @example
* // Example: A NumberInputWidget.
* var numberInput = new OO.ui.NumberInputWidget( {
* label: 'NumberInputWidget',
* input: { value: 5 },
* min: 1,
* max: 10
* } );
* $( 'body' ).append( numberInput.$element );
*
* @class
* @extends OO.ui.Widget
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
* @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
* @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
* @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
* @cfg {number} [min=-Infinity] Minimum allowed value
* @cfg {number} [max=Infinity] Maximum allowed value
* @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
* @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
* @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
*/
OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
// Configuration initialization
config = $.extend( {
isInteger: false,
min: -Infinity,
max: Infinity,
step: 1,
pageStep: null,
showButtons: true
}, config );
// Parent constructor
OO.ui.NumberInputWidget.parent.call( this, config );
// Properties
this.input = new OO.ui.TextInputWidget( $.extend(
{
disabled: this.isDisabled(),
type: 'number'
},
config.input
) );
if ( config.showButtons ) {
this.minusButton = new OO.ui.ButtonWidget( $.extend(
{
disabled: this.isDisabled(),
tabIndex: -1,
classes: [ 'oo-ui-numberInputWidget-minusButton' ],
label: '−'
},
config.minusButton
) );
this.plusButton = new OO.ui.ButtonWidget( $.extend(
{
disabled: this.isDisabled(),
tabIndex: -1,
classes: [ 'oo-ui-numberInputWidget-plusButton' ],
label: '+'
},
config.plusButton
) );
}
// Events
this.input.connect( this, {
change: this.emit.bind( this, 'change' ),
enter: this.emit.bind( this, 'enter' )
} );
this.input.$input.on( {
keydown: this.onKeyDown.bind( this ),
'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
} );
if ( config.showButtons ) {
this.plusButton.connect( this, {
click: [ 'onButtonClick', +1 ]
} );
this.minusButton.connect( this, {
click: [ 'onButtonClick', -1 ]
} );
}
// Initialization
this.setIsInteger( !!config.isInteger );
this.setRange( config.min, config.max );
this.setStep( config.step, config.pageStep );
this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
.append( this.input.$element );
this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
if ( config.showButtons ) {
this.$field
.prepend( this.minusButton.$element )
.append( this.plusButton.$element );
this.$element.addClass( 'oo-ui-numberInputWidget-buttoned' );
}
this.input.setValidation( this.validateNumber.bind( this ) );
};
/* Setup */
OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
/* Events */
/**
* A `change` event is emitted when the value of the input changes.
*
* @event change
*/
/**
* An `enter` event is emitted when the user presses 'enter' inside the text box.
*
* @event enter
*/
/* Methods */
/**
* Set whether only integers are allowed
*
* @param {boolean} flag
*/
OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
this.isInteger = !!flag;
this.input.setValidityFlag();
};
/**
* Get whether only integers are allowed
*
* @return {boolean} Flag value
*/
OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
return this.isInteger;
};
/**
* Set the range of allowed values
*
* @param {number} min Minimum allowed value
* @param {number} max Maximum allowed value
*/
OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
if ( min > max ) {
throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
}
this.min = min;
this.max = max;
this.input.setValidityFlag();
};
/**
* Get the current range
*
* @return {number[]} Minimum and maximum values
*/
OO.ui.NumberInputWidget.prototype.getRange = function () {
return [ this.min, this.max ];
};
/**
* Set the stepping deltas
*
* @param {number} step Normal step
* @param {number|null} pageStep Page step. If null, 10 * step will be used.
*/
OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
if ( step <= 0 ) {
throw new Error( 'Step value must be positive' );
}
if ( pageStep === null ) {
pageStep = step * 10;
} else if ( pageStep <= 0 ) {
throw new Error( 'Page step value must be positive' );
}
this.step = step;
this.pageStep = pageStep;
};
/**
* Get the current stepping values
*
* @return {number[]} Step and page step
*/
OO.ui.NumberInputWidget.prototype.getStep = function () {
return [ this.step, this.pageStep ];
};
/**
* Get the current value of the widget
*
* @return {string}
*/
OO.ui.NumberInputWidget.prototype.getValue = function () {
return this.input.getValue();
};
/**
* Get the current value of the widget as a number
*
* @return {number} May be NaN, or an invalid number
*/
OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
return +this.input.getValue();
};
/**
* Set the value of the widget
*
* @param {string} value Invalid values are allowed
*/
OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
this.input.setValue( value );
};
/**
* Adjust the value of the widget
*
* @param {number} delta Adjustment amount
*/
OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
var n, v = this.getNumericValue();
delta = +delta;
if ( isNaN( delta ) || !isFinite( delta ) ) {
throw new Error( 'Delta must be a finite number' );
}
if ( isNaN( v ) ) {
n = 0;
} else {
n = v + delta;
n = Math.max( Math.min( n, this.max ), this.min );
if ( this.isInteger ) {
n = Math.round( n );
}
}
if ( n !== v ) {
this.setValue( n );
}
};
/**
* Validate input
*
* @private
* @param {string} value Field value
* @return {boolean}
*/
OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
var n = +value;
if ( isNaN( n ) || !isFinite( n ) ) {
return false;
}
if ( this.isInteger && Math.floor( n ) !== n ) {
return false;
}
if ( n < this.min || n > this.max ) {
return false;
}
return true;
};
/**
* Handle mouse click events.
*
* @private
* @param {number} dir +1 or -1
*/
OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
this.adjustValue( dir * this.step );
};
/**
* Handle mouse wheel events.
*
* @private
* @param {jQuery.Event} event
*/
OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
var delta = 0;
if ( !this.isDisabled() && this.input.$input.is( ':focus' ) ) {
// Standard 'wheel' event
if ( event.originalEvent.deltaMode !== undefined ) {
this.sawWheelEvent = true;
}
if ( event.originalEvent.deltaY ) {
delta = -event.originalEvent.deltaY;
} else if ( event.originalEvent.deltaX ) {
delta = event.originalEvent.deltaX;
}
// Non-standard events
if ( !this.sawWheelEvent ) {
if ( event.originalEvent.wheelDeltaX ) {
delta = -event.originalEvent.wheelDeltaX;
} else if ( event.originalEvent.wheelDeltaY ) {
delta = event.originalEvent.wheelDeltaY;
} else if ( event.originalEvent.wheelDelta ) {
delta = event.originalEvent.wheelDelta;
} else if ( event.originalEvent.detail ) {
delta = -event.originalEvent.detail;
}
}
if ( delta ) {
delta = delta < 0 ? -1 : 1;
this.adjustValue( delta * this.step );
}
return false;
}
};
/**
* Handle key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
if ( !this.isDisabled() ) {
switch ( e.which ) {
case OO.ui.Keys.UP:
this.adjustValue( this.step );
return false;
case OO.ui.Keys.DOWN:
this.adjustValue( -this.step );
return false;
case OO.ui.Keys.PAGEUP:
this.adjustValue( this.pageStep );
return false;
case OO.ui.Keys.PAGEDOWN:
this.adjustValue( -this.pageStep );
return false;
}
}
};
/**
* @inheritdoc
*/
OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
// Parent method
OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
if ( this.input ) {
this.input.setDisabled( this.isDisabled() );
}
if ( this.minusButton ) {
this.minusButton.setDisabled( this.isDisabled() );
}
if ( this.plusButton ) {
this.plusButton.setDisabled( this.isDisabled() );
}
return this;
};
}( OO ) );
/*!
* OOjs UI v0.19.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-02-14T22:47:20Z
*/
( function ( OO ) {
'use strict';
/**
* Toolbars are complex interface components that permit users to easily access a variety
* of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
* part of the toolbar, but not configured as tools.
*
* Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
* the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
* image’), and an icon.
*
* Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
* of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
* The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
* any order, but each can only appear once in the toolbar.
*
* The toolbar can be synchronized with the state of the external "application", like a text
* editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
* active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
* tool would be disabled while the user is not editing a table). A state change is signalled by
* emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
* {@link OO.ui.Tool#onUpdateState onUpdateState method}.
*
* The following is an example of a basic toolbar.
*
* @example
* // Example of a toolbar
* // Create the toolbar
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Toolbar example' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.parent.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // Register two more tools, nothing interesting here
* function SettingsTool() {
* SettingsTool.parent.apply( this, arguments );
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* this.setActive( false );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.parent.apply( this, arguments );
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* this.setActive( false );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget).
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools' icons only, side-by-side.
* type: 'bar',
* include: [ 'search', 'help' ]
* },
* {
* // 'list' tool groups display both the titles and icons, in a dropdown list.
* type: 'list',
* indicator: 'down',
* label: 'More',
* include: [ 'settings', 'stuff' ]
* }
* // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
* // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
* // since it's more complicated to use. (See the next example snippet on this page.)
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( 'body' ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
* {@link #event-updateState 'updateState' event}.
*
* @example
* // Create the toolbar
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Toolbar example' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.parent.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // Register two more tools, nothing interesting here
* function SettingsTool() {
* SettingsTool.parent.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.parent.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools' icons only, side-by-side.
* type: 'bar',
* include: [ 'search', 'help' ]
* },
* {
* // 'menu' tool groups display both the titles and icons, in a dropdown menu.
* // Menu label indicates which items are selected.
* type: 'menu',
* indicator: 'down',
* include: [ 'settings', 'stuff' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( 'body' ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
* @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
* @param {Object} [config] Configuration options
* @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
* in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
* the toolbar.
* @cfg {string} [position='top'] Whether the toolbar is positioned above ('top') or below ('bottom') content.
*/
OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
config = toolFactory;
toolFactory = config.toolFactory;
toolGroupFactory = config.toolGroupFactory;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Toolbar.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.toolFactory = toolFactory;
this.toolGroupFactory = toolGroupFactory;
this.groups = [];
this.tools = {};
this.position = config.position || 'top';
this.$bar = $( '<div>' );
this.$actions = $( '<div>' );
this.initialized = false;
this.narrowThreshold = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
// Events
this.$element
.add( this.$bar ).add( this.$group ).add( this.$actions )
.on( 'mousedown keydown', this.onPointerDown.bind( this ) );
// Initialization
this.$group.addClass( 'oo-ui-toolbar-tools' );
if ( config.actions ) {
this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
}
this.$bar
.addClass( 'oo-ui-toolbar-bar' )
.append( this.$group, '<div style="clear:both"></div>' );
this.$element.addClass( 'oo-ui-toolbar oo-ui-toolbar-position-' + this.position ).append( this.$bar );
};
/* Setup */
OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
/* Events */
/**
* @event updateState
*
* An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`)
* every time the state of the application using the toolbar changes, and an update to the state of
* tools is required.
*
* @param {...Mixed} data Application-defined parameters
*/
/* Methods */
/**
* Get the tool factory.
*
* @return {OO.ui.ToolFactory} Tool factory
*/
OO.ui.Toolbar.prototype.getToolFactory = function () {
return this.toolFactory;
};
/**
* Get the toolgroup factory.
*
* @return {OO.Factory} Toolgroup factory
*/
OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
return this.toolGroupFactory;
};
/**
* Handles mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
$closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
return false;
}
};
/**
* Handle window resize event.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.Toolbar.prototype.onWindowResize = function () {
this.$element.toggleClass(
'oo-ui-toolbar-narrow',
this.$bar.width() <= this.getNarrowThreshold()
);
};
/**
* Get the (lazily-computed) width threshold for applying the oo-ui-toolbar-narrow
* class.
*
* @private
* @return {number} Width threshold in pixels
*/
OO.ui.Toolbar.prototype.getNarrowThreshold = function () {
if ( this.narrowThreshold === null ) {
this.narrowThreshold = this.$group.width() + this.$actions.width();
}
return this.narrowThreshold;
};
/**
* Sets up handles and preloads required information for the toolbar to work.
* This must be called after it is attached to a visible document and before doing anything else.
*/
OO.ui.Toolbar.prototype.initialize = function () {
if ( !this.initialized ) {
this.initialized = true;
$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
this.onWindowResize();
}
};
/**
* Set up the toolbar.
*
* The toolbar is set up with a list of toolgroup configurations that specify the type of
* toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
* to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
* see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
*
* @param {Object.<string,Array>} groups List of toolgroup configurations
* @param {Array|string} [groups.include] Tools to include in the toolgroup
* @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
* @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
* @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
*/
OO.ui.Toolbar.prototype.setup = function ( groups ) {
var i, len, type, group,
items = [],
defaultType = 'bar';
// Cleanup previous groups
this.reset();
// Build out new groups
for ( i = 0, len = groups.length; i < len; i++ ) {
group = groups[ i ];
if ( group.include === '*' ) {
// Apply defaults to catch-all groups
if ( group.type === undefined ) {
group.type = 'list';
}
if ( group.label === undefined ) {
group.label = OO.ui.msg( 'ooui-toolbar-more' );
}
}
// Check type has been registered
type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
items.push(
this.getToolGroupFactory().create( type, this, group )
);
}
this.addItems( items );
};
/**
* Remove all tools and toolgroups from the toolbar.
*/
OO.ui.Toolbar.prototype.reset = function () {
var i, len;
this.groups = [];
this.tools = {};
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].destroy();
}
this.clearItems();
};
/**
* Destroy the toolbar.
*
* Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
* this method whenever you are done using a toolbar.
*/
OO.ui.Toolbar.prototype.destroy = function () {
$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
this.reset();
this.$element.remove();
};
/**
* Check if the tool is available.
*
* Available tools are ones that have not yet been added to the toolbar.
*
* @param {string} name Symbolic name of tool
* @return {boolean} Tool is available
*/
OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
return !this.tools[ name ];
};
/**
* Prevent tool from being used again.
*
* @param {OO.ui.Tool} tool Tool to reserve
*/
OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
this.tools[ tool.getName() ] = tool;
};
/**
* Allow tool to be used again.
*
* @param {OO.ui.Tool} tool Tool to release
*/
OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
delete this.tools[ tool.getName() ];
};
/**
* Get accelerator label for tool.
*
* The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
* use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
* that describes the accelerator keys for the tool passed (by symbolic name) to the method.
*
* @param {string} name Symbolic name of tool
* @return {string|undefined} Tool accelerator label if available
*/
OO.ui.Toolbar.prototype.getToolAccelerator = function () {
return undefined;
};
/**
* Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
* Each tool is configured with a static name, title, and icon and is customized with the command to carry
* out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
* which creates the tools on demand.
*
* Every Tool subclass must implement two methods:
*
* - {@link #onUpdateState}
* - {@link #onSelect}
*
* Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
* {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
* the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
*
* For more information, please see the [OOjs UI documentation on MediaWiki][1].
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
* @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
* the {@link #static-title static title} property is used.
*
* The title is used in different ways depending on the type of toolgroup that contains the tool. The
* title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is
* part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
*
* For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
* is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
* To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
*/
OO.ui.Tool = function OoUiTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Tool.parent.call( this, config );
// Properties
this.toolGroup = toolGroup;
this.toolbar = this.toolGroup.getToolbar();
this.active = false;
this.$title = $( '<span>' );
this.$accel = $( '<span>' );
this.$link = $( '<a>' );
this.title = null;
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
// Events
this.toolbar.connect( this, { updateState: 'onUpdateState' } );
// Initialization
this.$title.addClass( 'oo-ui-tool-title' );
this.$accel
.addClass( 'oo-ui-tool-accel' )
.prop( {
// This may need to be changed if the key names are ever localized,
// but for now they are essentially written in English
dir: 'ltr',
lang: 'en'
} );
this.$link
.addClass( 'oo-ui-tool-link' )
.append( this.$icon, this.$title, this.$accel )
.attr( 'role', 'button' );
this.$element
.data( 'oo-ui-tool', this )
.addClass(
'oo-ui-tool ' + 'oo-ui-tool-name-' +
this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
)
.toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
.append( this.$link );
this.setTitle( config.title || this.constructor.static.title );
};
/* Setup */
OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.Tool.static.tagName = 'span';
/**
* Symbolic name of tool.
*
* The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
* also be used when adding tools to toolgroups.
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Tool.static.name = '';
/**
* Symbolic name of the group.
*
* The group name is used to associate tools with each other so that they can be selected later by
* a {@link OO.ui.ToolGroup toolgroup}.
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Tool.static.group = '';
/**
* Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used.
*
* @abstract
* @static
* @inheritable
* @property {string|Function}
*/
OO.ui.Tool.static.title = '';
/**
* Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
* Normally only the icon is displayed, or only the label if no icon is given.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.Tool.static.displayBothIconAndLabel = false;
/**
* Add tool to catch-all groups automatically.
*
* A catch-all group, which contains all tools that do not currently belong to a toolgroup,
* can be included in a toolgroup using the wildcard selector, an asterisk (*).
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.Tool.static.autoAddToCatchall = true;
/**
* Add tool to named groups automatically.
*
* By default, tools that are configured with a static ‘group’ property are added
* to that group and will be selected when the symbolic name of the group is specified (e.g., when
* toolgroups include tools by group name).
*
* @static
* @property {boolean}
* @inheritable
*/
OO.ui.Tool.static.autoAddToGroup = true;
/**
* Check if this tool is compatible with given data.
*
* This is a stub that can be overridden to provide support for filtering tools based on an
* arbitrary piece of information (e.g., where the cursor is in a document). The implementation
* must also call this method so that the compatibility check can be performed.
*
* @static
* @inheritable
* @param {Mixed} data Data to check
* @return {boolean} Tool can be used with data
*/
OO.ui.Tool.static.isCompatibleWith = function () {
return false;
};
/* Methods */
/**
* Handle the toolbar state being updated. This method is called when the
* {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
* {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
* depending on application state (usually by calling #setDisabled to enable or disable the tool,
* or #setActive to mark is as currently in-use or not).
*
* This is an abstract method that must be overridden in a concrete subclass.
*
* @method
* @protected
* @abstract
*/
OO.ui.Tool.prototype.onUpdateState = null;
/**
* Handle the tool being selected. This method is called when the user triggers this tool,
* usually by clicking on its label/icon.
*
* This is an abstract method that must be overridden in a concrete subclass.
*
* @method
* @protected
* @abstract
*/
OO.ui.Tool.prototype.onSelect = null;
/**
* Check if the tool is active.
*
* Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
* with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
*
* @return {boolean} Tool is active
*/
OO.ui.Tool.prototype.isActive = function () {
return this.active;
};
/**
* Make the tool appear active or inactive.
*
* This method should be called within #onSelect or #onUpdateState event handlers to make the tool
* appear pressed or not.
*
* @param {boolean} state Make tool appear active
*/
OO.ui.Tool.prototype.setActive = function ( state ) {
this.active = !!state;
if ( this.active ) {
this.$element.addClass( 'oo-ui-tool-active' );
this.setFlags( { progressive: true } );
} else {
this.$element.removeClass( 'oo-ui-tool-active' );
this.setFlags( { progressive: false } );
}
};
/**
* Set the tool #title.
*
* @param {string|Function} title Title text or a function that returns text
* @chainable
*/
OO.ui.Tool.prototype.setTitle = function ( title ) {
this.title = OO.ui.resolveMsg( title );
this.updateTitle();
return this;
};
/**
* Get the tool #title.
*
* @return {string} Title text
*/
OO.ui.Tool.prototype.getTitle = function () {
return this.title;
};
/**
* Get the tool's symbolic name.
*
* @return {string} Symbolic name of tool
*/
OO.ui.Tool.prototype.getName = function () {
return this.constructor.static.name;
};
/**
* Update the title.
*/
OO.ui.Tool.prototype.updateTitle = function () {
var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
accelTooltips = this.toolGroup.constructor.static.accelTooltips,
accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
tooltipParts = [];
this.$title.text( this.title );
this.$accel.text( accel );
if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
tooltipParts.push( this.title );
}
if ( accelTooltips && typeof accel === 'string' && accel.length ) {
tooltipParts.push( accel );
}
if ( tooltipParts.length ) {
this.$link.attr( 'title', tooltipParts.join( ' ' ) );
} else {
this.$link.removeAttr( 'title' );
}
};
/**
* Destroy tool.
*
* Destroying the tool removes all event handlers and the tool’s DOM elements.
* Call this method whenever you are done using a tool.
*/
OO.ui.Tool.prototype.destroy = function () {
this.toolbar.disconnect( this );
this.$element.remove();
};
/**
* ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
* The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
* to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
* themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
*
* Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
* using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
* The options `exclude`, `promote`, and `demote` support the same formats.
*
* See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
* please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
* @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
* @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above.
* @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
* This setting is particularly useful when tools have been added to the toolgroup
* en masse (e.g., via the catch-all selector).
*/
OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ToolGroup.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.toolbar = toolbar;
this.tools = {};
this.pressed = null;
this.autoDisabled = false;
this.include = config.include || [];
this.exclude = config.exclude || [];
this.promote = config.promote || [];
this.demote = config.demote || [];
this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
// Events
this.$element.on( {
mousedown: this.onMouseKeyDown.bind( this ),
mouseup: this.onMouseKeyUp.bind( this ),
keydown: this.onMouseKeyDown.bind( this ),
keyup: this.onMouseKeyUp.bind( this ),
focus: this.onMouseOverFocus.bind( this ),
blur: this.onMouseOutBlur.bind( this ),
mouseover: this.onMouseOverFocus.bind( this ),
mouseout: this.onMouseOutBlur.bind( this )
} );
this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
this.aggregate( { disable: 'itemDisable' } );
this.connect( this, { itemDisable: 'updateDisabled' } );
// Initialization
this.$group.addClass( 'oo-ui-toolGroup-tools' );
this.$element
.addClass( 'oo-ui-toolGroup' )
.append( this.$group );
this.populate();
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
/* Events */
/**
* @event update
*/
/* Static Properties */
/**
* Show labels in tooltips.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.titleTooltips = false;
/**
* Show acceleration labels in tooltips.
*
* Note: The OOjs UI library does not include an accelerator system, but does contain
* a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
* override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
* meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.accelTooltips = false;
/**
* Automatically disable the toolgroup when all tools are disabled
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.autoDisable = true;
/**
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ToolGroup.static.name = null;
/* Methods */
/**
* @inheritdoc
*/
OO.ui.ToolGroup.prototype.isDisabled = function () {
return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
};
/**
* @inheritdoc
*/
OO.ui.ToolGroup.prototype.updateDisabled = function () {
var i, item, allDisabled = true;
if ( this.constructor.static.autoDisable ) {
for ( i = this.items.length - 1; i >= 0; i-- ) {
item = this.items[ i ];
if ( !item.isDisabled() ) {
allDisabled = false;
break;
}
}
this.autoDisabled = allDisabled;
}
OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
};
/**
* Handle mouse down and key down events.
*
* @protected
* @param {jQuery.Event} e Mouse down or key down event
*/
OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
if (
!this.isDisabled() &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
this.pressed = this.getTargetTool( e );
if ( this.pressed ) {
this.pressed.setActive( true );
this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
}
return false;
}
};
/**
* Handle captured mouse up and key up events.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
// onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
// released, but since `this.pressed` will no longer be true, the second call will be ignored.
this.onMouseKeyUp( e );
};
/**
* Handle mouse up and key up events.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
var tool = this.getTargetTool( e );
if (
!this.isDisabled() && this.pressed && this.pressed === tool &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
this.pressed.onSelect();
this.pressed = null;
e.preventDefault();
e.stopPropagation();
}
this.pressed = null;
};
/**
* Handle mouse over and focus events.
*
* @protected
* @param {jQuery.Event} e Mouse over or focus event
*/
OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
var tool = this.getTargetTool( e );
if ( this.pressed && this.pressed === tool ) {
this.pressed.setActive( true );
}
};
/**
* Handle mouse out and blur events.
*
* @protected
* @param {jQuery.Event} e Mouse out or blur event
*/
OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
var tool = this.getTargetTool( e );
if ( this.pressed && this.pressed === tool ) {
this.pressed.setActive( false );
}
};
/**
* Get the closest tool to a jQuery.Event.
*
* Only tool links are considered, which prevents other elements in the tool such as popups from
* triggering tool group interactions.
*
* @private
* @param {jQuery.Event} e
* @return {OO.ui.Tool|null} Tool, `null` if none was found
*/
OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
var tool,
$item = $( e.target ).closest( '.oo-ui-tool-link' );
if ( $item.length ) {
tool = $item.parent().data( 'oo-ui-tool' );
}
return tool && !tool.isDisabled() ? tool : null;
};
/**
* Handle tool registry register events.
*
* If a tool is registered after the group is created, we must repopulate the list to account for:
*
* - a tool being added that may be included
* - a tool already included being overridden
*
* @protected
* @param {string} name Symbolic name of tool
*/
OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
this.populate();
};
/**
* Get the toolbar that contains the toolgroup.
*
* @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
*/
OO.ui.ToolGroup.prototype.getToolbar = function () {
return this.toolbar;
};
/**
* Add and remove tools based on configuration.
*/
OO.ui.ToolGroup.prototype.populate = function () {
var i, len, name, tool,
toolFactory = this.toolbar.getToolFactory(),
names = {},
add = [],
remove = [],
list = this.toolbar.getToolFactory().getTools(
this.include, this.exclude, this.promote, this.demote
);
// Build a list of needed tools
for ( i = 0, len = list.length; i < len; i++ ) {
name = list[ i ];
if (
// Tool exists
toolFactory.lookup( name ) &&
// Tool is available or is already in this group
( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
) {
// Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
// creating it, but we can't call reserveTool() yet because we haven't created the tool.
this.toolbar.tools[ name ] = true;
tool = this.tools[ name ];
if ( !tool ) {
// Auto-initialize tools on first use
this.tools[ name ] = tool = toolFactory.create( name, this );
tool.updateTitle();
}
this.toolbar.reserveTool( tool );
add.push( tool );
names[ name ] = true;
}
}
// Remove tools that are no longer needed
for ( name in this.tools ) {
if ( !names[ name ] ) {
this.tools[ name ].destroy();
this.toolbar.releaseTool( this.tools[ name ] );
remove.push( this.tools[ name ] );
delete this.tools[ name ];
}
}
if ( remove.length ) {
this.removeItems( remove );
}
// Update emptiness state
if ( add.length ) {
this.$element.removeClass( 'oo-ui-toolGroup-empty' );
} else {
this.$element.addClass( 'oo-ui-toolGroup-empty' );
}
// Re-add tools (moving existing ones to new locations)
this.addItems( add );
// Disabled state may depend on items
this.updateDisabled();
};
/**
* Destroy toolgroup.
*/
OO.ui.ToolGroup.prototype.destroy = function () {
var name;
this.clearItems();
this.toolbar.getToolFactory().disconnect( this );
for ( name in this.tools ) {
this.toolbar.releaseTool( this.tools[ name ] );
this.tools[ name ].disconnect( this ).destroy();
delete this.tools[ name ];
}
this.$element.remove();
};
/**
* A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
* and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
* registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
*
* For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @class
* @extends OO.Factory
* @constructor
*/
OO.ui.ToolFactory = function OoUiToolFactory() {
// Parent constructor
OO.ui.ToolFactory.parent.call( this );
};
/* Setup */
OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
/* Methods */
/**
* Get tools from the factory
*
* @param {Array|string} [include] Included tools, see #extract for format
* @param {Array|string} [exclude] Excluded tools, see #extract for format
* @param {Array|string} [promote] Promoted tools, see #extract for format
* @param {Array|string} [demote] Demoted tools, see #extract for format
* @return {string[]} List of tools
*/
OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
var i, len, included, promoted, demoted,
auto = [],
used = {};
// Collect included and not excluded tools
included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
// Promotion
promoted = this.extract( promote, used );
demoted = this.extract( demote, used );
// Auto
for ( i = 0, len = included.length; i < len; i++ ) {
if ( !used[ included[ i ] ] ) {
auto.push( included[ i ] );
}
}
return promoted.concat( auto ).concat( demoted );
};
/**
* Get a flat list of names from a list of names or groups.
*
* Normally, `collection` is an array of tool specifications. Tools can be specified in the
* following ways:
*
* - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
* - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
* tool to a group, use OO.ui.Tool.static.group.)
*
* Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
* catch-all selector `'*'`.
*
* If `used` is passed, tool names that appear as properties in this object will be considered
* already assigned, and will not be returned even if specified otherwise. The tool names extracted
* by this function call will be added as new properties in the object.
*
* @private
* @param {Array|string} collection List of tools, see above
* @param {Object} [used] Object containing information about used tools, see above
* @return {string[]} List of extracted tool names
*/
OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
var i, len, item, name, tool,
names = [];
collection = !Array.isArray( collection ) ? [ collection ] : collection;
for ( i = 0, len = collection.length; i < len; i++ ) {
item = collection[ i ];
if ( item === '*' ) {
for ( name in this.registry ) {
tool = this.registry[ name ];
if (
// Only add tools by group name when auto-add is enabled
tool.static.autoAddToCatchall &&
// Exclude already used tools
( !used || !used[ name ] )
) {
names.push( name );
if ( used ) {
used[ name ] = true;
}
}
}
} else {
// Allow plain strings as shorthand for named tools
if ( typeof item === 'string' ) {
item = { name: item };
}
if ( OO.isPlainObject( item ) ) {
if ( item.group ) {
for ( name in this.registry ) {
tool = this.registry[ name ];
if (
// Include tools with matching group
tool.static.group === item.group &&
// Only add tools by group name when auto-add is enabled
tool.static.autoAddToGroup &&
// Exclude already used tools
( !used || !used[ name ] )
) {
names.push( name );
if ( used ) {
used[ name ] = true;
}
}
}
// Include tools with matching name and exclude already used tools
} else if ( item.name && ( !used || !used[ item.name ] ) ) {
names.push( item.name );
if ( used ) {
used[ item.name ] = true;
}
}
}
}
}
return names;
};
/**
* ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
* specify a symbolic name and be registered with the factory. The following classes are registered by
* default:
*
* - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
* - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
* - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
*
* See {@link OO.ui.Toolbar toolbars} for an example.
*
* For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @class
* @extends OO.Factory
* @constructor
*/
OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
var i, l, defaultClasses;
// Parent constructor
OO.Factory.call( this );
defaultClasses = this.constructor.static.getDefaultClasses();
// Register default toolgroups
for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
this.register( defaultClasses[ i ] );
}
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
/* Static Methods */
/**
* Get a default set of classes to be registered on construction.
*
* @return {Function[]} Default classes
*/
OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
return [
OO.ui.BarToolGroup,
OO.ui.ListToolGroup,
OO.ui.MenuToolGroup
];
};
/**
* Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
* with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify
* an #onSelect or #onUpdateState method, as these methods have been implemented already.
*
* // Example of a popup tool. When selected, a popup tool displays
* // a popup window.
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* };
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
* toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Tool
* @mixins OO.ui.mixin.PopupElement
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
*/
OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Parent constructor
OO.ui.PopupTool.parent.call( this, toolGroup, config );
// Mixin constructors
OO.ui.mixin.PopupElement.call( this, config );
// Initialization
this.$element
.addClass( 'oo-ui-popupTool' )
.append( this.popup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
/* Methods */
/**
* Handle the tool being selected.
*
* @inheritdoc
*/
OO.ui.PopupTool.prototype.onSelect = function () {
if ( !this.isDisabled() ) {
this.popup.toggle();
}
this.setActive( false );
return false;
};
/**
* Handle the toolbar state being updated.
*
* @inheritdoc
*/
OO.ui.PopupTool.prototype.onUpdateState = function () {
this.setActive( false );
};
/**
* A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
* and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
* inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
* the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
* when the ToolGroupTool is selected.
*
* // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
*
* function SettingsTool() {
* SettingsTool.parent.apply( this, arguments );
* };
* OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.static.groupConfig = {
* icon: 'settings',
* label: 'ToolGroupTool',
* include: [ 'setting1', 'setting2' ]
* };
* toolFactory.register( SettingsTool );
*
* For more information, please see the [OOjs UI documentation on MediaWiki][1].
*
* Please note that this implementation is subject to change per [T74159] [2].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
* [2]: https://phabricator.wikimedia.org/T74159
*
* @abstract
* @class
* @extends OO.ui.Tool
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
*/
OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Parent constructor
OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
// Properties
this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
// Events
this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
// Initialization
this.$link.remove();
this.$element
.addClass( 'oo-ui-toolGroupTool' )
.append( this.innerToolGroup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
/* Static Properties */
/**
* Toolgroup configuration.
*
* The toolgroup configuration consists of the tools to include, as well as an icon and label
* to use for the bar item. Tools can be included by symbolic name, group, or with the
* wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
*
* @property {Object.<string,Array>}
*/
OO.ui.ToolGroupTool.static.groupConfig = {};
/* Methods */
/**
* Handle the tool being selected.
*
* @inheritdoc
*/
OO.ui.ToolGroupTool.prototype.onSelect = function () {
this.innerToolGroup.setActive( !this.innerToolGroup.active );
return false;
};
/**
* Synchronize disabledness state of the tool with the inner toolgroup.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
this.setDisabled( disabled );
};
/**
* Handle the toolbar state being updated.
*
* @inheritdoc
*/
OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
this.setActive( false );
};
/**
* Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
*
* @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
* more information.
* @return {OO.ui.ListToolGroup}
*/
OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
if ( group.include === '*' ) {
// Apply defaults to catch-all groups
if ( group.label === undefined ) {
group.label = OO.ui.msg( 'ooui-toolbar-more' );
}
}
return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
};
/**
* BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
* and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
* displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
* the tool.
*
* BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
* set up.
*
* @example
* // Example of a BarToolGroup with two tools
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.parent.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget).
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools by icon only
* type: 'bar',
* include: [ 'search', 'help' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( 'body' ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
*
* For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
* For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @class
* @extends OO.ui.ToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
*/
OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Parent constructor
OO.ui.BarToolGroup.parent.call( this, toolbar, config );
// Initialization
this.$element.addClass( 'oo-ui-barToolGroup' );
};
/* Setup */
OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.titleTooltips = true;
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.accelTooltips = true;
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.name = 'bar';
/**
* PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
* and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
* optional icon and label. This class can be used for other base classes that also use this functionality.
*
* @abstract
* @class
* @extends OO.ui.ToolGroup
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.ClippableElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {string} [header] Text to display at the top of the popup
*/
OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = $.extend( {
indicator: toolbar.position === 'bottom' ? 'up' : 'down'
}, config );
// Parent constructor
OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
// Properties
this.active = false;
this.dragging = false;
this.onBlurHandler = this.onBlur.bind( this );
this.$handle = $( '<span>' );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, config );
OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
// Events
this.$handle.on( {
keydown: this.onHandleMouseKeyDown.bind( this ),
keyup: this.onHandleMouseKeyUp.bind( this ),
mousedown: this.onHandleMouseKeyDown.bind( this ),
mouseup: this.onHandleMouseKeyUp.bind( this )
} );
// Initialization
this.$handle
.addClass( 'oo-ui-popupToolGroup-handle' )
.append( this.$icon, this.$label, this.$indicator );
// If the pop-up should have a header, add it to the top of the toolGroup.
// Note: If this feature is useful for other widgets, we could abstract it into an
// OO.ui.HeaderedElement mixin constructor.
if ( config.header !== undefined ) {
this.$group
.prepend( $( '<span>' )
.addClass( 'oo-ui-popupToolGroup-header' )
.text( config.header )
);
}
this.$element
.addClass( 'oo-ui-popupToolGroup' )
.prepend( this.$handle );
};
/* Setup */
OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* @inheritdoc
*/
OO.ui.PopupToolGroup.prototype.setDisabled = function () {
// Parent method
OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
if ( this.isDisabled() && this.isElementAttached() ) {
this.setActive( false );
}
};
/**
* Handle focus being lost.
*
* The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
// Only deactivate when clicking outside the dropdown element
if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
this.setActive( false );
}
};
/**
* @inheritdoc
*/
OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
// Only close toolgroup when a tool was actually selected
if (
!this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
this.setActive( false );
}
return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
};
/**
* Handle mouse up and key up events.
*
* @protected
* @param {jQuery.Event} e Mouse up or key up event
*/
OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
if (
!this.isDisabled() &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
return false;
}
};
/**
* Handle mouse down and key down events.
*
* @protected
* @param {jQuery.Event} e Mouse down or key down event
*/
OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
if (
!this.isDisabled() &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
this.setActive( !this.active );
return false;
}
};
/**
* Switch into 'active' mode.
*
* When active, the popup is visible. A mouseup event anywhere in the document will trigger
* deactivation.
*
* @param {boolean} value The active state to set
*/
OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
var containerWidth, containerLeft;
value = !!value;
if ( this.active !== value ) {
this.active = value;
if ( value ) {
this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true );
this.$clippable.css( 'left', '' );
// Try anchoring the popup to the left first
this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
this.toggleClipping( true );
if ( this.isClippedHorizontally() ) {
// Anchoring to the left caused the popup to clip, so anchor it to the right instead
this.toggleClipping( false );
this.$element
.removeClass( 'oo-ui-popupToolGroup-left' )
.addClass( 'oo-ui-popupToolGroup-right' );
this.toggleClipping( true );
}
if ( this.isClippedHorizontally() ) {
// Anchoring to the right also caused the popup to clip, so just make it fill the container
containerWidth = this.$clippableScrollableContainer.width();
containerLeft = this.$clippableScrollableContainer.offset().left;
this.toggleClipping( false );
this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
this.$clippable.css( {
left: -( this.$element.offset().left - containerLeft ),
width: containerWidth
} );
}
} else {
this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true );
this.$element.removeClass(
'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
);
this.toggleClipping( false );
}
}
};
/**
* ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
* and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
* by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
* with a label, icon, indicator, header, and title.
*
* ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
* users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
* users to collapse the list again.
*
* ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
* requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
* information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
*
* @example
* // Example of a ListToolGroup
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // Configure and register two tools
* function SettingsTool() {
* SettingsTool.parent.apply( this, arguments );
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* this.setActive( false );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.parent.apply( this, arguments );
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'search';
* StuffTool.static.title = 'Change the world';
* StuffTool.prototype.onSelect = function () {
* this.setActive( false );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
* toolbar.setup( [
* {
* // Configurations for list toolgroup.
* type: 'list',
* label: 'ListToolGroup',
* icon: 'ellipsis',
* title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
* header: 'This is the header',
* include: [ 'settings', 'stuff' ],
* allowCollapse: ['stuff']
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* frame.$element.append(
* toolbar.$element
* );
* $( 'body' ).append( frame.$element );
* // Build the toolbar. This must be done after the toolbar has been appended to the document.
* toolbar.initialize();
*
* For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @class
* @extends OO.ui.PopupToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
* will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
* the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
* are included in the toolgroup, but are not designated as collapsible, will always be displayed.
* To open a collapsible list in its expanded state, set #expanded to 'true'.
* @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
* Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
* @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
* been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
* when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
*/
OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Properties (must be set before parent constructor, which calls #populate)
this.allowCollapse = config.allowCollapse;
this.forceExpand = config.forceExpand;
this.expanded = config.expanded !== undefined ? config.expanded : false;
this.collapsibleTools = [];
// Parent constructor
OO.ui.ListToolGroup.parent.call( this, toolbar, config );
// Initialization
this.$element.addClass( 'oo-ui-listToolGroup' );
};
/* Setup */
OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ListToolGroup.static.name = 'list';
/* Methods */
/**
* @inheritdoc
*/
OO.ui.ListToolGroup.prototype.populate = function () {
var i, len, allowCollapse = [];
OO.ui.ListToolGroup.parent.prototype.populate.call( this );
// Update the list of collapsible tools
if ( this.allowCollapse !== undefined ) {
allowCollapse = this.allowCollapse;
} else if ( this.forceExpand !== undefined ) {
allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
}
this.collapsibleTools = [];
for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
}
}
// Keep at the end, even when tools are added
this.$group.append( this.getExpandCollapseTool().$element );
this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
this.updateCollapsibleState();
};
/**
* Get the expand/collapse tool for this group
*
* @return {OO.ui.Tool} Expand collapse tool
*/
OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
var ExpandCollapseTool;
if ( this.expandCollapseTool === undefined ) {
ExpandCollapseTool = function () {
ExpandCollapseTool.parent.apply( this, arguments );
};
OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
ExpandCollapseTool.prototype.onSelect = function () {
this.toolGroup.expanded = !this.toolGroup.expanded;
this.toolGroup.updateCollapsibleState();
this.setActive( false );
};
ExpandCollapseTool.prototype.onUpdateState = function () {
// Do nothing. Tool interface requires an implementation of this function.
};
ExpandCollapseTool.static.name = 'more-fewer';
this.expandCollapseTool = new ExpandCollapseTool( this );
}
return this.expandCollapseTool;
};
/**
* @inheritdoc
*/
OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
// Do not close the popup when the user wants to show more/fewer tools
if (
$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
) {
// HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
// hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
} else {
return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
}
};
OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
var i, len;
this.getExpandCollapseTool()
.setIcon( this.expanded ? 'collapse' : 'expand' )
.setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
this.collapsibleTools[ i ].toggle( this.expanded );
}
};
/**
* MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
* and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
* which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
* menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
* the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
*
* MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
* is set up.
*
* @example
* // Example of a MenuToolGroup
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
*
* // Define the tools that we're going to place in our toolbar
*
* function SettingsTool() {
* SettingsTool.parent.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* function StuffTool() {
* StuffTool.parent.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* type: 'menu',
* header: 'This is the (optional) header',
* title: 'This is the (optional) title',
* include: [ 'settings', 'stuff' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( 'body' ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
* For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
*
* @class
* @extends OO.ui.PopupToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
*/
OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
// Events
this.toolbar.connect( this, { updateState: 'onUpdateState' } );
// Initialization
this.$element.addClass( 'oo-ui-menuToolGroup' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuToolGroup.static.name = 'menu';
/* Methods */
/**
* Handle the toolbar state being updated.
*
* When the state changes, the title of each active item in the menu will be joined together and
* used as a label for the group. The label will be empty if none of the items are active.
*
* @private
*/
OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
var name,
labelTexts = [];
for ( name in this.tools ) {
if ( this.tools[ name ].isActive() ) {
labelTexts.push( this.tools[ name ].getTitle() );
}
}
this.setLabel( labelTexts.join( ', ' ) || ' ' );
};
}( OO ) );
/*!
* OOjs UI v0.19.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-02-14T22:47:20Z
*/
( function ( OO ) {
'use strict';
/**
* An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
* Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
* of the actions.
*
* Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
* @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
* should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
* for more information about setting modes.
* @cfg {boolean} [framed=false] Render the action button with a frame
*/
OO.ui.ActionWidget = function OoUiActionWidget( config ) {
// Configuration initialization
config = $.extend( { framed: false }, config );
// Parent constructor
OO.ui.ActionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this, config );
// Properties
this.action = config.action || '';
this.modes = config.modes || [];
this.width = 0;
this.height = 0;
// Initialization
this.$element.addClass( 'oo-ui-actionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
/* Events */
/**
* A resize event is emitted when the size of the widget changes.
*
* @event resize
*/
/* Methods */
/**
* Check if the action is configured to be available in the specified `mode`.
*
* @param {string} mode Name of mode
* @return {boolean} The action is configured with the mode
*/
OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
return this.modes.indexOf( mode ) !== -1;
};
/**
* Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
*
* @return {string}
*/
OO.ui.ActionWidget.prototype.getAction = function () {
return this.action;
};
/**
* Get the symbolic name of the mode or modes for which the action is configured to be available.
*
* The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
* Only actions that are configured to be avaiable in the current mode will be visible. All other actions
* are hidden.
*
* @return {string[]}
*/
OO.ui.ActionWidget.prototype.getModes = function () {
return this.modes.slice();
};
/**
* Emit a resize event if the size has changed.
*
* @private
* @chainable
*/
OO.ui.ActionWidget.prototype.propagateResize = function () {
var width, height;
if ( this.isElementAttached() ) {
width = this.$element.width();
height = this.$element.height();
if ( width !== this.width || height !== this.height ) {
this.width = width;
this.height = height;
this.emit( 'resize' );
}
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.ActionWidget.prototype.setIcon = function () {
// Mixin method
OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
this.propagateResize();
return this;
};
/**
* @inheritdoc
*/
OO.ui.ActionWidget.prototype.setLabel = function () {
// Mixin method
OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
this.propagateResize();
return this;
};
/**
* @inheritdoc
*/
OO.ui.ActionWidget.prototype.setFlags = function () {
// Mixin method
OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
this.propagateResize();
return this;
};
/**
* @inheritdoc
*/
OO.ui.ActionWidget.prototype.clearFlags = function () {
// Mixin method
OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
this.propagateResize();
return this;
};
/**
* Toggle the visibility of the action button.
*
* @param {boolean} [show] Show button, omit to toggle visibility
* @chainable
*/
OO.ui.ActionWidget.prototype.toggle = function () {
// Parent method
OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
this.propagateResize();
return this;
};
/* eslint-disable no-unused-vars */
/**
* ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
* Actions can be made available for specific contexts (modes) and circumstances
* (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
*
* ActionSets contain two types of actions:
*
* - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
* - Other: Other actions include all non-special visible actions.
*
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
*
* @example
* // Example: An action set used in a process dialog
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
* MyProcessDialog.static.title = 'An action set in a process dialog';
* MyProcessDialog.static.name = 'myProcessDialog';
* // An action set that uses modes ('edit' and 'help' mode, in this example).
* MyProcessDialog.static.actions = [
* { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
* { action: 'help', modes: 'edit', label: 'Help' },
* { modes: 'edit', label: 'Cancel', flags: 'safe' },
* { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
* this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
* this.stackLayout = new OO.ui.StackLayout( {
* items: [ this.panel1, this.panel2 ]
* } );
* this.$body.append( this.stackLayout.$element );
* };
* MyProcessDialog.prototype.getSetupProcess = function ( data ) {
* return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
* .next( function () {
* this.actions.setMode( 'edit' );
* }, this );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* if ( action === 'help' ) {
* this.actions.setMode( 'help' );
* this.stackLayout.setItem( this.panel2 );
* } else if ( action === 'back' ) {
* this.actions.setMode( 'edit' );
* this.stackLayout.setItem( this.panel1 );
* } else if ( action === 'continue' ) {
* var dialog = this;
* return new OO.ui.Process( function () {
* dialog.close();
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
* MyProcessDialog.prototype.getBodyHeight = function () {
* return this.panel1.$element.outerHeight( true );
* };
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* var dialog = new MyProcessDialog( {
* size: 'medium'
* } );
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @abstract
* @class
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ActionSet = function OoUiActionSet( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.list = [];
this.categories = {
actions: 'getAction',
flags: 'getFlags',
modes: 'getModes'
};
this.categorized = {};
this.special = {};
this.others = [];
this.organized = false;
this.changing = false;
this.changed = false;
};
/* eslint-enable no-unused-vars */
/* Setup */
OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the flags used to identify special actions. Special actions are displayed in the
* header of a {@link OO.ui.ProcessDialog process dialog}.
* See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
*
* [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
/* Events */
/**
* @event click
*
* A 'click' event is emitted when an action is clicked.
*
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
/**
* @event resize
*
* A 'resize' event is emitted when an action widget is resized.
*
* @param {OO.ui.ActionWidget} action Action that was resized
*/
/**
* @event add
*
* An 'add' event is emitted when actions are {@link #method-add added} to the action set.
*
* @param {OO.ui.ActionWidget[]} added Actions added
*/
/**
* @event remove
*
* A 'remove' event is emitted when actions are {@link #method-remove removed}
* or {@link #clear cleared}.
*
* @param {OO.ui.ActionWidget[]} added Actions removed
*/
/**
* @event change
*
* A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
* or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
*
*/
/* Methods */
/**
* Handle action change events.
*
* @private
* @fires change
*/
OO.ui.ActionSet.prototype.onActionChange = function () {
this.organized = false;
if ( this.changing ) {
this.changed = true;
} else {
this.emit( 'change' );
}
};
/**
* Check if an action is one of the special actions.
*
* @param {OO.ui.ActionWidget} action Action to check
* @return {boolean} Action is special
*/
OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
var flag;
for ( flag in this.special ) {
if ( action === this.special[ flag ] ) {
return true;
}
}
return false;
};
/**
* Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
* or ‘disabled’.
*
* @param {Object} [filters] Filters to use, omit to get all actions
* @param {string|string[]} [filters.actions] Actions that action widgets must have
* @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
* @param {string|string[]} [filters.modes] Modes that action widgets must have
* @param {boolean} [filters.visible] Action widgets must be visible
* @param {boolean} [filters.disabled] Action widgets must be disabled
* @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
*/
OO.ui.ActionSet.prototype.get = function ( filters ) {
var i, len, list, category, actions, index, match, matches;
if ( filters ) {
this.organize();
// Collect category candidates
matches = [];
for ( category in this.categorized ) {
list = filters[ category ];
if ( list ) {
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( i = 0, len = list.length; i < len; i++ ) {
actions = this.categorized[ category ][ list[ i ] ];
if ( Array.isArray( actions ) ) {
matches.push.apply( matches, actions );
}
}
}
}
// Remove by boolean filters
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
if (
( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
) {
matches.splice( i, 1 );
len--;
i--;
}
}
// Remove duplicates
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
index = matches.lastIndexOf( match );
while ( index !== i ) {
matches.splice( index, 1 );
len--;
index = matches.lastIndexOf( match );
}
}
return matches;
}
return this.list.slice();
};
/**
* Get 'special' actions.
*
* Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
* Special flags can be configured in subclasses by changing the static #specialFlags property.
*
* @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
*/
OO.ui.ActionSet.prototype.getSpecial = function () {
this.organize();
return $.extend( {}, this.special );
};
/**
* Get 'other' actions.
*
* Other actions include all non-special visible action widgets.
*
* @return {OO.ui.ActionWidget[]} 'Other' action widgets
*/
OO.ui.ActionSet.prototype.getOthers = function () {
this.organize();
return this.others.slice();
};
/**
* Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
* to be available in the specified mode will be made visible. All other actions will be hidden.
*
* @param {string} mode The mode. Only actions configured to be available in the specified
* mode will be made visible.
* @chainable
* @fires toggle
* @fires change
*/
OO.ui.ActionSet.prototype.setMode = function ( mode ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.toggle( action.hasMode( mode ) );
}
this.organized = false;
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Set the abilities of the specified actions.
*
* Action widgets that are configured with the specified actions will be enabled
* or disabled based on the boolean values specified in the `actions`
* parameter.
*
* @param {Object.<string,boolean>} actions A list keyed by action name with boolean
* values that indicate whether or not the action should be enabled.
* @chainable
*/
OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
var i, len, action, item;
for ( i = 0, len = this.list.length; i < len; i++ ) {
item = this.list[ i ];
action = item.getAction();
if ( actions[ action ] !== undefined ) {
item.setDisabled( !actions[ action ] );
}
}
return this;
};
/**
* Executes a function once per action.
*
* When making changes to multiple actions, use this method instead of iterating over the actions
* manually to defer emitting a #change event until after all actions have been changed.
*
* @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
* @param {Function} callback Callback to run for each action; callback is invoked with three
* arguments: the action, the action's index, the list of actions being iterated over
* @chainable
*/
OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
this.changed = false;
this.changing = true;
this.get( filter ).forEach( callback );
this.changing = false;
if ( this.changed ) {
this.emit( 'change' );
}
return this;
};
/**
* Add action widgets to the action set.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to add
* @chainable
* @fires add
* @fires change
*/
OO.ui.ActionSet.prototype.add = function ( actions ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
action.connect( this, {
click: [ 'emit', 'click', action ],
resize: [ 'emit', 'resize', action ],
toggle: [ 'onActionChange' ]
} );
this.list.push( action );
}
this.organized = false;
this.emit( 'add', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove action widgets from the set.
*
* To remove all actions, you may wish to use the #clear method instead.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to remove
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.remove = function ( actions ) {
var i, len, index, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
index = this.list.indexOf( action );
if ( index !== -1 ) {
action.disconnect( this );
this.list.splice( index, 1 );
}
}
this.organized = false;
this.emit( 'remove', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove all action widets from the set.
*
* To remove only specified actions, use the {@link #method-remove remove} method instead.
*
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.clear = function () {
var i, len, action,
removed = this.list.slice();
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.disconnect( this );
}
this.list = [];
this.organized = false;
this.emit( 'remove', removed );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Organize actions.
*
* This is called whenever organized information is requested. It will only reorganize the actions
* if something has changed since the last time it ran.
*
* @private
* @chainable
*/
OO.ui.ActionSet.prototype.organize = function () {
var i, iLen, j, jLen, flag, action, category, list, item, special,
specialFlags = this.constructor.static.specialFlags;
if ( !this.organized ) {
this.categorized = {};
this.special = {};
this.others = [];
for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
action = this.list[ i ];
if ( action.isVisible() ) {
// Populate categories
for ( category in this.categories ) {
if ( !this.categorized[ category ] ) {
this.categorized[ category ] = {};
}
list = action[ this.categories[ category ] ]();
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( j = 0, jLen = list.length; j < jLen; j++ ) {
item = list[ j ];
if ( !this.categorized[ category ][ item ] ) {
this.categorized[ category ][ item ] = [];
}
this.categorized[ category ][ item ].push( action );
}
}
// Populate special/others
special = false;
for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
flag = specialFlags[ j ];
if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
this.special[ flag ] = action;
special = true;
break;
}
}
if ( !special ) {
this.others.push( action );
}
}
}
this.organized = true;
}
return this;
};
/**
* Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
* in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
* appearance and functionality of the error interface.
*
* The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
* is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
* that initiated the failed process will be disabled.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
* process again.
*
* For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
*
* @class
*
* @constructor
* @param {string|jQuery} message Description of error
* @param {Object} [config] Configuration options
* @cfg {boolean} [recoverable=true] Error is recoverable.
* By default, errors are recoverable, and users can try the process again.
* @cfg {boolean} [warning=false] Error is a warning.
* If the error is a warning, the error interface will include a
* 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
* is not triggered a second time if the user chooses to continue.
*/
OO.ui.Error = function OoUiError( message, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( message ) && config === undefined ) {
config = message;
message = config.message;
}
// Configuration initialization
config = config || {};
// Properties
this.message = message instanceof jQuery ? message : String( message );
this.recoverable = config.recoverable === undefined || !!config.recoverable;
this.warning = !!config.warning;
};
/* Setup */
OO.initClass( OO.ui.Error );
/* Methods */
/**
* Check if the error is recoverable.
*
* If the error is recoverable, users are able to try the process again.
*
* @return {boolean} Error is recoverable
*/
OO.ui.Error.prototype.isRecoverable = function () {
return this.recoverable;
};
/**
* Check if the error is a warning.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
*
* @return {boolean} Error is warning
*/
OO.ui.Error.prototype.isWarning = function () {
return this.warning;
};
/**
* Get error message as DOM nodes.
*
* @return {jQuery} Error message in DOM nodes
*/
OO.ui.Error.prototype.getMessage = function () {
return this.message instanceof jQuery ?
this.message.clone() :
$( '<div>' ).text( this.message ).contents();
};
/**
* Get the error message text.
*
* @return {string} Error message
*/
OO.ui.Error.prototype.getMessageText = function () {
return this.message instanceof jQuery ? this.message.text() : this.message;
};
/**
* A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
* or a function:
*
* - **number**: the process will wait for the specified number of milliseconds before proceeding.
* - **promise**: the process will continue to the next step when the promise is successfully resolved
* or stop if the promise is rejected.
* - **function**: the process will execute the function. The process will stop if the function returns
* either a boolean `false` or a promise that is rejected; if the function returns a number, the process
* will wait for that number of milliseconds before proceeding.
*
* If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
* configured, users can dismiss the error and try the process again, or not. If a process is stopped,
* its remaining steps will not be performed.
*
* @class
*
* @constructor
* @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
* that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
* @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
* a number or promise.
*/
OO.ui.Process = function ( step, context ) {
// Properties
this.steps = [];
// Initialization
if ( step !== undefined ) {
this.next( step, context );
}
};
/* Setup */
OO.initClass( OO.ui.Process );
/* Methods */
/**
* Start the process.
*
* @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
* If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
* and any remaining steps are not performed.
*/
OO.ui.Process.prototype.execute = function () {
var i, len, promise;
/**
* Continue execution.
*
* @ignore
* @param {Array} step A function and the context it should be called in
* @return {Function} Function that continues the process
*/
function proceed( step ) {
return function () {
// Execute step in the correct context
var deferred,
result = step.callback.call( step.context );
if ( result === false ) {
// Use rejected promise for boolean false results
return $.Deferred().reject( [] ).promise();
}
if ( typeof result === 'number' ) {
if ( result < 0 ) {
throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
}
// Use a delayed promise for numbers, expecting them to be in milliseconds
deferred = $.Deferred();
setTimeout( deferred.resolve, result );
return deferred.promise();
}
if ( result instanceof OO.ui.Error ) {
// Use rejected promise for error
return $.Deferred().reject( [ result ] ).promise();
}
if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
// Use rejected promise for list of errors
return $.Deferred().reject( result ).promise();
}
// Duck-type the object to see if it can produce a promise
if ( result && $.isFunction( result.promise ) ) {
// Use a promise generated from the result
return result.promise();
}
// Use resolved promise for other results
return $.Deferred().resolve().promise();
};
}
if ( this.steps.length ) {
// Generate a chain reaction of promises
promise = proceed( this.steps[ 0 ] )();
for ( i = 1, len = this.steps.length; i < len; i++ ) {
promise = promise.then( proceed( this.steps[ i ] ) );
}
} else {
promise = $.Deferred().resolve().promise();
}
return promise;
};
/**
* Create a process step.
*
* @private
* @param {number|jQuery.Promise|Function} step
*
* - Number of milliseconds to wait before proceeding
* - Promise that must be resolved before proceeding
* - Function to execute
* - If the function returns a boolean false the process will stop
* - If the function returns a promise, the process will continue to the next
* step when the promise is resolved or stop if the promise is rejected
* - If the function returns a number, the process will wait for that number of
* milliseconds before proceeding
* @param {Object} [context=null] Execution context of the function. The context is
* ignored if the step is a number or promise.
* @return {Object} Step object, with `callback` and `context` properties
*/
OO.ui.Process.prototype.createStep = function ( step, context ) {
if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
return {
callback: function () {
return step;
},
context: null
};
}
if ( $.isFunction( step ) ) {
return {
callback: step,
context: context
};
}
throw new Error( 'Cannot create process step: number, promise or function expected' );
};
/**
* Add step to the beginning of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.first = function ( step, context ) {
this.steps.unshift( this.createStep( step, context ) );
return this;
};
/**
* Add step to the end of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.next = function ( step, context ) {
this.steps.push( this.createStep( step, context ) );
return this;
};
/**
* Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
* Managed windows are mutually exclusive. If a new window is opened while a current window is opening
* or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
* themselves are persistent and—rather than being torn down when closed—can be repopulated with the
* pertinent data and reused.
*
* Over the lifecycle of a window, the window manager makes available three promises: `opening`,
* `opened`, and `closing`, which represent the primary stages of the cycle:
*
* **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
* {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
*
* - an `opening` event is emitted with an `opening` promise
* - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
* the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
* window and its result executed
* - a `setup` progress notification is emitted from the `opening` promise
* - the #getReadyDelay method is called the returned value is used to time a pause in execution before
* the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
* window and its result executed
* - a `ready` progress notification is emitted from the `opening` promise
* - the `opening` promise is resolved with an `opened` promise
*
* **Opened**: the window is now open.
*
* **Closing**: the closing stage begins when the window manager's #closeWindow or the
* window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
* to close the window.
*
* - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
* - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
* window and its result executed
* - a `hold` progress notification is emitted from the `closing` promise
* - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
* window and its result executed
* - a `teardown` progress notification is emitted from the `closing` promise
* - the `closing` promise is resolved. The window is now closed
*
* See the [OOjs UI documentation on MediaWiki][1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
* Note that window classes that are instantiated with a factory must have
* a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
* @cfg {boolean} [modal=true] Prevent interaction outside the dialog
*/
OO.ui.WindowManager = function OoUiWindowManager( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.WindowManager.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.factory = config.factory;
this.modal = config.modal === undefined || !!config.modal;
this.windows = {};
this.opening = null;
this.opened = null;
this.closing = null;
this.preparingToOpen = null;
this.preparingToClose = null;
this.currentWindow = null;
this.globalEvents = false;
this.$returnFocusTo = null;
this.$ariaHidden = null;
this.onWindowResizeTimeout = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
// Initialization
this.$element
.addClass( 'oo-ui-windowManager' )
.toggleClass( 'oo-ui-windowManager-modal', this.modal );
};
/* Setup */
OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
/* Events */
/**
* An 'opening' event is emitted when the window begins to be opened.
*
* @event opening
* @param {OO.ui.Window} win Window that's being opened
* @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
* When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
* is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
* @param {Object} data Window opening data
*/
/**
* A 'closing' event is emitted when the window begins to be closed.
*
* @event closing
* @param {OO.ui.Window} win Window that's being closed
* @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
* is closed successfully. The promise emits `hold` and `teardown` notifications when those
* processes are complete. When the `closing` promise is resolved, the first argument of its value
* is the closing data.
* @param {Object} data Window closing data
*/
/**
* A 'resize' event is emitted when a window is resized.
*
* @event resize
* @param {OO.ui.Window} win Window that was resized
*/
/* Static Properties */
/**
* Map of the symbolic name of each window size and its CSS properties.
*
* @static
* @inheritable
* @property {Object}
*/
OO.ui.WindowManager.static.sizes = {
small: {
width: 300
},
medium: {
width: 500
},
large: {
width: 700
},
larger: {
width: 900
},
full: {
// These can be non-numeric because they are never used in calculations
width: '100%',
height: '100%'
}
};
/**
* Symbolic name of the default window size.
*
* The default size is used if the window's requested size is not recognized.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.WindowManager.static.defaultSize = 'medium';
/* Methods */
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.onWindowResize = function () {
clearTimeout( this.onWindowResizeTimeout );
this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
};
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.afterWindowResize = function () {
if ( this.currentWindow ) {
this.updateWindowSize( this.currentWindow );
}
};
/**
* Check if window is opening.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opening
*/
OO.ui.WindowManager.prototype.isOpening = function ( win ) {
return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
};
/**
* Check if window is closing.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is closing
*/
OO.ui.WindowManager.prototype.isClosing = function ( win ) {
return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
};
/**
* Check if window is opened.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opened
*/
OO.ui.WindowManager.prototype.isOpened = function ( win ) {
return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
};
/**
* Check if a window is being managed.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is being managed
*/
OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
var name;
for ( name in this.windows ) {
if ( this.windows[ name ] === win ) {
return true;
}
}
return false;
};
/**
* Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getSetupDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getReadyDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getHoldDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after the ‘hold’ process has finished before
* executing the ‘teardown’ process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getTeardownDelay = function () {
return this.modal ? 250 : 0;
};
/**
* Get a window by its symbolic name.
*
* If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
* instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
* for more information about using factories.
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @param {string} name Symbolic name of the window
* @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
* @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
* @throws {Error} An error is thrown if the named window is not recognized as a managed window.
*/
OO.ui.WindowManager.prototype.getWindow = function ( name ) {
var deferred = $.Deferred(),
win = this.windows[ name ];
if ( !( win instanceof OO.ui.Window ) ) {
if ( this.factory ) {
if ( !this.factory.lookup( name ) ) {
deferred.reject( new OO.ui.Error(
'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
) );
} else {
win = this.factory.create( name );
this.addWindows( [ win ] );
deferred.resolve( win );
}
} else {
deferred.reject( new OO.ui.Error(
'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
) );
}
} else {
deferred.resolve( win );
}
return deferred.promise();
};
/**
* Get current window.
*
* @return {OO.ui.Window|null} Currently opening/opened/closing window
*/
OO.ui.WindowManager.prototype.getCurrentWindow = function () {
return this.currentWindow;
};
/**
* Open a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to open
* @param {Object} [data] Window opening data
* @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when closed.
* Defaults the current activeElement. If set to null, focus isn't changed on close.
* @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
* See {@link #event-opening 'opening' event} for more information about `opening` promises.
* @fires opening
*/
OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
var manager = this,
opening = $.Deferred();
data = data || {};
// Argument handling
if ( typeof win === 'string' ) {
return this.getWindow( win ).then( function ( win ) {
return manager.openWindow( win, data );
} );
}
// Error handling
if ( !this.hasWindow( win ) ) {
opening.reject( new OO.ui.Error(
'Cannot open window: window is not attached to manager'
) );
} else if ( this.preparingToOpen || this.opening || this.opened ) {
opening.reject( new OO.ui.Error(
'Cannot open window: another window is opening or open'
) );
}
// Window opening
if ( opening.state() !== 'rejected' ) {
// If a window is currently closing, wait for it to complete
this.preparingToOpen = $.when( this.closing );
// Ensure handlers get called after preparingToOpen is set
this.preparingToOpen.done( function () {
if ( manager.modal ) {
manager.toggleGlobalEvents( true );
manager.toggleAriaIsolation( true );
}
manager.$returnFocusTo = data.$returnFocusTo || $( document.activeElement );
manager.currentWindow = win;
manager.opening = opening;
manager.preparingToOpen = null;
manager.emit( 'opening', win, opening, data );
setTimeout( function () {
win.setup( data ).then( function () {
manager.updateWindowSize( win );
manager.opening.notify( { state: 'setup' } );
setTimeout( function () {
win.ready( data ).then( function () {
manager.opening.notify( { state: 'ready' } );
manager.opening = null;
manager.opened = $.Deferred();
opening.resolve( manager.opened.promise(), data );
}, function () {
manager.opening = null;
manager.opened = $.Deferred();
opening.reject();
manager.closeWindow( win );
} );
}, manager.getReadyDelay() );
}, function () {
manager.opening = null;
manager.opened = $.Deferred();
opening.reject();
manager.closeWindow( win );
} );
}, manager.getSetupDelay() );
} );
}
return opening.promise();
};
/**
* Close a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to close
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
* See {@link #event-closing 'closing' event} for more information about closing promises.
* @throws {Error} An error is thrown if the window is not managed by the window manager.
* @fires closing
*/
OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
var manager = this,
closing = $.Deferred(),
opened;
// Argument handling
if ( typeof win === 'string' ) {
win = this.windows[ win ];
} else if ( !this.hasWindow( win ) ) {
win = null;
}
// Error handling
if ( !win ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window is not attached to manager'
) );
} else if ( win !== this.currentWindow ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window already closed with different data'
) );
} else if ( this.preparingToClose || this.closing ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window already closing with different data'
) );
}
// Window closing
if ( closing.state() !== 'rejected' ) {
// If the window is currently opening, close it when it's done
this.preparingToClose = $.when( this.opening );
// Ensure handlers get called after preparingToClose is set
this.preparingToClose.always( function () {
manager.closing = closing;
manager.preparingToClose = null;
manager.emit( 'closing', win, closing, data );
opened = manager.opened;
manager.opened = null;
opened.resolve( closing.promise(), data );
setTimeout( function () {
win.hold( data ).then( function () {
closing.notify( { state: 'hold' } );
setTimeout( function () {
win.teardown( data ).then( function () {
closing.notify( { state: 'teardown' } );
if ( manager.modal ) {
manager.toggleGlobalEvents( false );
manager.toggleAriaIsolation( false );
}
if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
manager.$returnFocusTo[ 0 ].focus();
}
manager.closing = null;
manager.currentWindow = null;
closing.resolve( data );
} );
}, manager.getTeardownDelay() );
} );
}, manager.getHoldDelay() );
} );
}
return closing.promise();
};
/**
* Add windows to the window manager.
*
* Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
* See the [OOjs ui documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* This function can be called in two manners:
*
* 1. `.addWindows( [ windowA, windowB, ... ] )` (where `windowA`, `windowB` are OO.ui.Window objects)
*
* This syntax registers windows under the symbolic names defined in their `.static.name`
* properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
* `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
* static name to be set, otherwise an exception will be thrown.
*
* This is the recommended way, as it allows for an easier switch to using a window factory.
*
* 2. `.addWindows( { nameA: windowA, nameB: windowB, ... } )`
*
* This syntax registers windows under the explicitly given symbolic names. In this example,
* calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
* its `.static.name` is set to. The static name is not required to be set.
*
* This should only be used if you need to override the default symbolic names.
*
* Example:
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* // Add a window under the default name: see OO.ui.MessageDialog.static.name
* windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
* // Add a window under an explicit name
* windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
*
* // Open window by default name
* windowManager.openWindow( 'message' );
* // Open window by explicitly given name
* windowManager.openWindow( 'myMessageDialog' );
*
*
* @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
* by reference, symbolic name, or explicitly defined symbolic names.
* @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
* explicit nor a statically configured symbolic name.
*/
OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
var i, len, win, name, list;
if ( Array.isArray( windows ) ) {
// Convert to map of windows by looking up symbolic names from static configuration
list = {};
for ( i = 0, len = windows.length; i < len; i++ ) {
name = windows[ i ].constructor.static.name;
if ( !name ) {
throw new Error( 'Windows must have a `name` static property defined.' );
}
list[ name ] = windows[ i ];
}
} else if ( OO.isPlainObject( windows ) ) {
list = windows;
}
// Add windows
for ( name in list ) {
win = list[ name ];
this.windows[ name ] = win.toggle( false );
this.$element.append( win.$element );
win.setManager( this );
}
};
/**
* Remove the specified windows from the windows manager.
*
* Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
* the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
* longer listens to events, use the #destroy method.
*
* @param {string[]} names Symbolic names of windows to remove
* @return {jQuery.Promise} Promise resolved when window is closed and removed
* @throws {Error} An error is thrown if the named windows are not managed by the window manager.
*/
OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
var i, len, win, name, cleanupWindow,
manager = this,
promises = [],
cleanup = function ( name, win ) {
delete manager.windows[ name ];
win.$element.detach();
};
for ( i = 0, len = names.length; i < len; i++ ) {
name = names[ i ];
win = this.windows[ name ];
if ( !win ) {
throw new Error( 'Cannot remove window' );
}
cleanupWindow = cleanup.bind( null, name, win );
promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
}
return $.when.apply( $, promises );
};
/**
* Remove all windows from the window manager.
*
* Windows will be closed before they are removed. Note that the window manager, though not in use, will still
* listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
* To remove just a subset of windows, use the #removeWindows method.
*
* @return {jQuery.Promise} Promise resolved when all windows are closed and removed
*/
OO.ui.WindowManager.prototype.clearWindows = function () {
return this.removeWindows( Object.keys( this.windows ) );
};
/**
* Set dialog size. In general, this method should not be called directly.
*
* Fullscreen mode will be used if the dialog is too wide to fit in the screen.
*
* @param {OO.ui.Window} win Window to update, should be the current window
* @chainable
*/
OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
var isFullscreen;
// Bypass for non-current, and thus invisible, windows
if ( win !== this.currentWindow ) {
return;
}
isFullscreen = win.getSize() === 'full';
this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
win.setDimensions( win.getSizeProperties() );
this.emit( 'resize', win );
return this;
};
/**
* Bind or unbind global events for scrolling.
*
* @private
* @param {boolean} [on] Bind global events
* @chainable
*/
OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
var scrollWidth, bodyMargin,
$body = $( this.getElementDocument().body ),
// We could have multiple window managers open so only modify
// the body css at the bottom of the stack
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
on = on === undefined ? !!this.globalEvents : !!on;
if ( on ) {
if ( !this.globalEvents ) {
$( this.getElementWindow() ).on( {
// Start listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
if ( stackDepth === 0 ) {
scrollWidth = window.innerWidth - document.documentElement.clientWidth;
bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
$body.css( {
overflow: 'hidden',
'margin-right': bodyMargin + scrollWidth
} );
}
stackDepth++;
this.globalEvents = true;
}
} else if ( this.globalEvents ) {
$( this.getElementWindow() ).off( {
// Stop listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
stackDepth--;
if ( stackDepth === 0 ) {
$body.css( {
overflow: '',
'margin-right': ''
} );
}
this.globalEvents = false;
}
$body.data( 'windowManagerGlobalEvents', stackDepth );
return this;
};
/**
* Toggle screen reader visibility of content other than the window manager.
*
* @private
* @param {boolean} [isolate] Make only the window manager visible to screen readers
* @chainable
*/
OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
if ( isolate ) {
if ( !this.$ariaHidden ) {
// Hide everything other than the window manager from screen readers
this.$ariaHidden = $( 'body' )
.children()
.not( this.$element.parentsUntil( 'body' ).last() )
.attr( 'aria-hidden', '' );
}
} else if ( this.$ariaHidden ) {
// Restore screen reader visibility
this.$ariaHidden.removeAttr( 'aria-hidden' );
this.$ariaHidden = null;
}
return this;
};
/**
* Destroy the window manager.
*
* Destroying the window manager ensures that it will no longer listen to events. If you would like to
* continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
* instead.
*/
OO.ui.WindowManager.prototype.destroy = function () {
this.toggleGlobalEvents( false );
this.toggleAriaIsolation( false );
this.clearWindows();
this.$element.remove();
};
/**
* A window is a container for elements that are in a child frame. They are used with
* a window manager (OO.ui.WindowManager), which is used to open and close the window and control
* its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
* ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
* the window manager will choose a sensible fallback.
*
* The lifecycle of a window has three primary stages (opening, opened, and closing) in which
* different processes are executed:
*
* **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
* openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
* the window.
*
* - {@link #getSetupProcess} method is called and its result executed
* - {@link #getReadyProcess} method is called and its result executed
*
* **opened**: The window is now open
*
* **closing**: The closing stage begins when the window manager's
* {@link OO.ui.WindowManager#closeWindow closeWindow}
* or the window's {@link #close} methods are used, and the window manager begins to close the window.
*
* - {@link #getHoldProcess} method is called and its result executed
* - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
*
* Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
* by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
* methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
* processing can complete. Always assume window processes are executed asynchronously.
*
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
* `full`. If omitted, the value of the {@link #static-size static size} property will be used.
*/
OO.ui.Window = function OoUiWindow( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Window.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.manager = null;
this.size = config.size || this.constructor.static.size;
this.$frame = $( '<div>' );
this.$overlay = $( '<div>' );
this.$content = $( '<div>' );
this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
// Initialization
this.$overlay.addClass( 'oo-ui-window-overlay' );
this.$content
.addClass( 'oo-ui-window-content' )
.attr( 'tabindex', 0 );
this.$frame
.addClass( 'oo-ui-window-frame' )
.append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
this.$element
.addClass( 'oo-ui-window' )
.append( this.$frame, this.$overlay );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.Window, OO.ui.Element );
OO.mixinClass( OO.ui.Window, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
*
* The static size is used if no #size is configured during construction.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Window.static.size = 'medium';
/* Methods */
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.Window.prototype.onMouseDown = function ( e ) {
// Prevent clicking on the click-block from stealing focus
if ( e.target === this.$element[ 0 ] ) {
return false;
}
};
/**
* Check if the window has been initialized.
*
* Initialization occurs when a window is added to a manager.
*
* @return {boolean} Window has been initialized
*/
OO.ui.Window.prototype.isInitialized = function () {
return !!this.manager;
};
/**
* Check if the window is visible.
*
* @return {boolean} Window is visible
*/
OO.ui.Window.prototype.isVisible = function () {
return this.visible;
};
/**
* Check if the window is opening.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
* method.
*
* @return {boolean} Window is opening
*/
OO.ui.Window.prototype.isOpening = function () {
return this.manager.isOpening( this );
};
/**
* Check if the window is closing.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
*
* @return {boolean} Window is closing
*/
OO.ui.Window.prototype.isClosing = function () {
return this.manager.isClosing( this );
};
/**
* Check if the window is opened.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
*
* @return {boolean} Window is opened
*/
OO.ui.Window.prototype.isOpened = function () {
return this.manager.isOpened( this );
};
/**
* Get the window manager.
*
* All windows must be attached to a window manager, which is used to open
* and close the window and control its presentation.
*
* @return {OO.ui.WindowManager} Manager of window
*/
OO.ui.Window.prototype.getManager = function () {
return this.manager;
};
/**
* Get the symbolic name of the window size (e.g., `small` or `medium`).
*
* @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
*/
OO.ui.Window.prototype.getSize = function () {
var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
sizes = this.manager.constructor.static.sizes,
size = this.size;
if ( !sizes[ size ] ) {
size = this.manager.constructor.static.defaultSize;
}
if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
size = 'full';
}
return size;
};
/**
* Get the size properties associated with the current window size
*
* @return {Object} Size properties
*/
OO.ui.Window.prototype.getSizeProperties = function () {
return this.manager.constructor.static.sizes[ this.getSize() ];
};
/**
* Disable transitions on window's frame for the duration of the callback function, then enable them
* back.
*
* @private
* @param {Function} callback Function to call while transitions are disabled
*/
OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
// We need to build the transition CSS properties using these specific properties since
// Firefox doesn't return anything useful when asked just for 'transition'.
var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
this.$frame.css( 'transition-duration' ) + ' ' +
this.$frame.css( 'transition-timing-function' ) + ' ' +
this.$frame.css( 'transition-delay' );
this.$frame.css( 'transition', 'none' );
callback();
// Force reflow to make sure the style changes done inside callback
// really are not transitioned
this.$frame.height();
this.$frame.css( 'transition', oldTransition );
};
/**
* Get the height of the full window contents (i.e., the window head, body and foot together).
*
* What consistitutes the head, body, and foot varies depending on the window type.
* A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
* and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
* and special actions in the head, and dialog content in the body.
*
* To get just the height of the dialog body, use the #getBodyHeight method.
*
* @return {number} The height of the window contents (the dialog head, body and foot) in pixels
*/
OO.ui.Window.prototype.getContentHeight = function () {
var bodyHeight,
win = this,
bodyStyleObj = this.$body[ 0 ].style,
frameStyleObj = this.$frame[ 0 ].style;
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
this.withoutSizeTransitions( function () {
var oldHeight = frameStyleObj.height,
oldPosition = bodyStyleObj.position;
frameStyleObj.height = '1px';
// Force body to resize to new width
bodyStyleObj.position = 'relative';
bodyHeight = win.getBodyHeight();
frameStyleObj.height = oldHeight;
bodyStyleObj.position = oldPosition;
} );
return (
// Add buffer for border
( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
// Use combined heights of children
( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
);
};
/**
* Get the height of the window body.
*
* To get the height of the full window contents (the window body, head, and foot together),
* use #getContentHeight.
*
* When this function is called, the window will temporarily have been resized
* to height=1px, so .scrollHeight measurements can be taken accurately.
*
* @return {number} Height of the window body in pixels
*/
OO.ui.Window.prototype.getBodyHeight = function () {
return this.$body[ 0 ].scrollHeight;
};
/**
* Get the directionality of the frame (right-to-left or left-to-right).
*
* @return {string} Directionality: `'ltr'` or `'rtl'`
*/
OO.ui.Window.prototype.getDir = function () {
return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
};
/**
* Get the 'setup' process.
*
* The setup process is used to set up a window for use in a particular context,
* based on the `data` argument. This method is called during the opening phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the ‘setup’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* To add window content that persists between openings, you may wish to use the #initialize method
* instead.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Setup process
*/
OO.ui.Window.prototype.getSetupProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘ready’ process.
*
* The ready process is used to ready a window for use in a particular
* context, based on the `data` argument. This method is called during the opening phase of
* the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
*
* Override this method to add additional steps to the ‘ready’ process the parent method
* provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
* methods of OO.ui.Process.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Ready process
*/
OO.ui.Window.prototype.getReadyProcess = function () {
return new OO.ui.Process();
};
/**
* Get the 'hold' process.
*
* The hold process is used to keep a window from being used in a particular context,
* based on the `data` argument. This method is called during the closing phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the 'hold' process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Hold process
*/
OO.ui.Window.prototype.getHoldProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘teardown’ process.
*
* The teardown process is used to teardown a window after use. During teardown,
* user interactions within the window are conveyed and the window is closed, based on the `data`
* argument. This method is called during the closing phase of the window’s lifecycle.
*
* Override this method to add additional steps to the ‘teardown’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Teardown process
*/
OO.ui.Window.prototype.getTeardownProcess = function () {
return new OO.ui.Process();
};
/**
* Set the window manager.
*
* This will cause the window to initialize. Calling it more than once will cause an error.
*
* @param {OO.ui.WindowManager} manager Manager for this window
* @throws {Error} An error is thrown if the method is called more than once
* @chainable
*/
OO.ui.Window.prototype.setManager = function ( manager ) {
if ( this.manager ) {
throw new Error( 'Cannot set window manager, window already has a manager' );
}
this.manager = manager;
this.initialize();
return this;
};
/**
* Set the window size by symbolic name (e.g., 'small' or 'medium')
*
* @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
* `full`
* @chainable
*/
OO.ui.Window.prototype.setSize = function ( size ) {
this.size = size;
this.updateSize();
return this;
};
/**
* Update the window size.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.updateSize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot update window size, must be attached to a manager' );
}
this.manager.updateWindowSize( this );
return this;
};
/**
* Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
* when the window is opening. In general, setDimensions should not be called directly.
*
* To set the size of the window, use the #setSize method.
*
* @param {Object} dim CSS dimension properties
* @param {string|number} [dim.width] Width
* @param {string|number} [dim.minWidth] Minimum width
* @param {string|number} [dim.maxWidth] Maximum width
* @param {string|number} [dim.height] Height, omit to set based on height of contents
* @param {string|number} [dim.minHeight] Minimum height
* @param {string|number} [dim.maxHeight] Maximum height
* @chainable
*/
OO.ui.Window.prototype.setDimensions = function ( dim ) {
var height,
win = this,
styleObj = this.$frame[ 0 ].style;
// Calculate the height we need to set using the correct width
if ( dim.height === undefined ) {
this.withoutSizeTransitions( function () {
var oldWidth = styleObj.width;
win.$frame.css( 'width', dim.width || '' );
height = win.getContentHeight();
styleObj.width = oldWidth;
} );
} else {
height = dim.height;
}
this.$frame.css( {
width: dim.width || '',
minWidth: dim.minWidth || '',
maxWidth: dim.maxWidth || '',
height: height || '',
minHeight: dim.minHeight || '',
maxHeight: dim.maxHeight || ''
} );
return this;
};
/**
* Initialize window contents.
*
* Before the window is opened for the first time, #initialize is called so that content that
* persists between openings can be added to the window.
*
* To set up a window with new content each time the window opens, use #getSetupProcess.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.initialize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot initialize window, must be attached to a manager' );
}
// Properties
this.$head = $( '<div>' );
this.$body = $( '<div>' );
this.$foot = $( '<div>' );
this.$document = $( this.getElementDocument() );
// Events
this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
// Initialization
this.$head.addClass( 'oo-ui-window-head' );
this.$body.addClass( 'oo-ui-window-body' );
this.$foot.addClass( 'oo-ui-window-foot' );
this.$content.append( this.$head, this.$body, this.$foot );
return this;
};
/**
* Called when someone tries to focus the hidden element at the end of the dialog.
* Sends focus back to the start of the dialog.
*
* @param {jQuery.Event} event Focus event
*/
OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
var backwards = this.$focusTrapBefore.is( event.target ),
element = OO.ui.findFocusable( this.$content, backwards );
if ( element ) {
// There's a focusable element inside the content, at the front or
// back depending on which focus trap we hit; select it.
element.focus();
} else {
// There's nothing focusable inside the content. As a fallback,
// this.$content is focusable, and focusing it will keep our focus
// properly trapped. It's not a *meaningful* focus, since it's just
// the content-div for the Window, but it's better than letting focus
// escape into the page.
this.$content.focus();
}
};
/**
* Open the window.
*
* This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
* method, which returns a promise resolved when the window is done opening.
*
* To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
* if the window fails to open. When the promise is resolved successfully, the first argument of the
* value is a new promise, which is resolved when the window begins closing.
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.open = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot open window, must be attached to a manager' );
}
return this.manager.openWindow( this, data );
};
/**
* Close the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
* which returns a closing promise resolved when the window is done closing.
*
* The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
* phase of the window’s lifecycle and can be used to specify closing behavior each time
* the window closes.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is closed
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.close = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot close window, must be attached to a manager' );
}
return this.manager.closeWindow( this, data );
};
/**
* Setup window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is setup
*/
OO.ui.Window.prototype.setup = function ( data ) {
var win = this;
this.toggle( true );
this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
this.$focusTraps.on( 'focus', this.focusTrapHandler );
return this.getSetupProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.addClass( 'oo-ui-window-content-setup' ).width();
} );
};
/**
* Ready window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is ready
*/
OO.ui.Window.prototype.ready = function ( data ) {
var win = this;
this.$content.focus();
return this.getReadyProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-ready' ).width();
win.$content.addClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Hold window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is held
*/
OO.ui.Window.prototype.hold = function ( data ) {
var win = this;
return this.getHoldProcess( data ).execute().then( function () {
// Get the focused element within the window's content
var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
// Blur the focused element
if ( $focus.length ) {
$focus[ 0 ].blur();
}
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-ready' ).width();
win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Teardown window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is torn down
*/
OO.ui.Window.prototype.teardown = function ( data ) {
var win = this;
return this.getTeardownProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
win.$focusTraps.off( 'focus', win.focusTrapHandler );
win.toggle( false );
} );
};
/**
* The Dialog class serves as the base class for the other types of dialogs.
* Unless extended to include controls, the rendered dialog box is a simple window
* that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
* which opens, closes, and controls the presentation of the window. See the
* [OOjs UI documentation on MediaWiki] [1] for more information.
*
* @example
* // A simple dialog window.
* function MyDialog( config ) {
* MyDialog.parent.call( this, config );
* }
* OO.inheritClass( MyDialog, OO.ui.Dialog );
* MyDialog.static.name = 'myDialog';
* MyDialog.prototype.initialize = function () {
* MyDialog.parent.prototype.initialize.call( this );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
* this.$body.append( this.content.$element );
* };
* MyDialog.prototype.getBodyHeight = function () {
* return this.content.$element.outerHeight( true );
* };
* var myDialog = new MyDialog( {
* size: 'medium'
* } );
* // Create and append a window manager, which opens and closes the window.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ myDialog ] );
* // Open the window!
* windowManager.openWindow( myDialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
*
* @abstract
* @class
* @extends OO.ui.Window
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Dialog = function OoUiDialog( config ) {
// Parent constructor
OO.ui.Dialog.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this );
// Properties
this.actions = new OO.ui.ActionSet();
this.attachedActions = [];
this.currentAction = null;
this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
// Events
this.actions.connect( this, {
click: 'onActionClick',
change: 'onActionsChange'
} );
// Initialization
this.$element
.addClass( 'oo-ui-dialog' )
.attr( 'role', 'dialog' );
};
/* Setup */
OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
/* Static Properties */
/**
* Symbolic name of dialog.
*
* The dialog class must have a symbolic name in order to be registered with OO.Factory.
* Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
*
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Dialog.static.name = '';
/**
* The dialog title.
*
* The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
* that will produce a Label node or string. The title can also be specified with data passed to the
* constructor (see #getSetupProcess). In this case, the static value will be overridden.
*
* @abstract
* @static
* @inheritable
* @property {jQuery|string|Function}
*/
OO.ui.Dialog.static.title = '';
/**
* An array of configured {@link OO.ui.ActionWidget action widgets}.
*
* Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
* value will be overridden.
*
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @static
* @inheritable
* @property {Object[]}
*/
OO.ui.Dialog.static.actions = [];
/**
* Close the dialog when the 'Esc' key is pressed.
*
* @static
* @abstract
* @inheritable
* @property {boolean}
*/
OO.ui.Dialog.static.escapable = true;
/* Methods */
/**
* Handle frame document key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
var actions;
if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
this.executeAction( '' );
e.preventDefault();
e.stopPropagation();
} else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
if ( actions.length > 0 ) {
this.executeAction( actions[ 0 ].getAction() );
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Handle action click events.
*
* @private
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
OO.ui.Dialog.prototype.onActionClick = function ( action ) {
if ( !this.isPending() ) {
this.executeAction( action.getAction() );
}
};
/**
* Handle actions change event.
*
* @private
*/
OO.ui.Dialog.prototype.onActionsChange = function () {
this.detachActions();
if ( !this.isClosing() ) {
this.attachActions();
}
};
/**
* Get the set of actions used by the dialog.
*
* @return {OO.ui.ActionSet}
*/
OO.ui.Dialog.prototype.getActions = function () {
return this.actions;
};
/**
* Get a process for taking action.
*
* When you override this method, you can create a new OO.ui.Process and return it, or add additional
* accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
* and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
*
* @param {string} [action] Symbolic name of action
* @return {OO.ui.Process} Action process
*/
OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
return new OO.ui.Process()
.next( function () {
if ( !action ) {
// An empty action always closes the dialog without data, which should always be
// safe and make no changes
this.close();
}
}, this );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
* the {@link #static-title static title}
* @param {Object[]} [data.actions] List of configuration options for each
* {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
*/
OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
var config = this.constructor.static,
actions = data.actions !== undefined ? data.actions : config.actions,
title = data.title !== undefined ? data.title : config.title;
this.title.setLabel( title ).setTitle( title );
this.actions.add( this.getActionWidgets( actions ) );
this.$element.on( 'keydown', this.onDialogKeyDownHandler );
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
this.$element.off( 'keydown', this.onDialogKeyDownHandler );
this.actions.clear();
this.currentAction = null;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.initialize = function () {
var titleId;
// Parent method
OO.ui.Dialog.parent.prototype.initialize.call( this );
titleId = OO.ui.generateElementId();
// Properties
this.title = new OO.ui.LabelWidget( {
id: titleId
} );
// Initialization
this.$content.addClass( 'oo-ui-dialog-content' );
this.$element.attr( 'aria-labelledby', titleId );
this.setPendingElement( this.$head );
};
/**
* Get action widgets from a list of configs
*
* @param {Object[]} actions Action widget configs
* @return {OO.ui.ActionWidget[]} Action widgets
*/
OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
var i, len, widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
widgets.push(
new OO.ui.ActionWidget( actions[ i ] )
);
}
return widgets;
};
/**
* Attach action actions.
*
* @protected
*/
OO.ui.Dialog.prototype.attachActions = function () {
// Remember the list of potentially attached actions
this.attachedActions = this.actions.get();
};
/**
* Detach action actions.
*
* @protected
* @chainable
*/
OO.ui.Dialog.prototype.detachActions = function () {
var i, len;
// Detach all actions that may have been previously attached
for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
this.attachedActions[ i ].$element.detach();
}
this.attachedActions = [];
};
/**
* Execute an action.
*
* @param {string} action Symbolic name of action to execute
* @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
*/
OO.ui.Dialog.prototype.executeAction = function ( action ) {
this.pushPending();
this.currentAction = action;
return this.getActionProcess( action ).execute()
.always( this.popPending.bind( this ) );
};
/**
* MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
* consists of a header that contains the dialog title, a body with the message, and a footer that
* contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
* of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
*
* There are two basic types of message dialogs, confirmation and alert:
*
* - **confirmation**: the dialog title describes what a progressive action will do and the message provides
* more details about the consequences.
* - **alert**: the dialog title describes which event occurred and the message provides more information
* about why the event occurred.
*
* The MessageDialog class specifies two actions: ‘accept’, the primary
* action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
* passing along the selected action.
*
* For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example: Creating and opening a message dialog window.
* var messageDialog = new OO.ui.MessageDialog();
*
* // Create and append a window manager.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ messageDialog ] );
* // Open the window.
* windowManager.openWindow( messageDialog, {
* title: 'Basic message dialog',
* message: 'This is the message'
* } );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
*
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
// Parent constructor
OO.ui.MessageDialog.parent.call( this, config );
// Properties
this.verticalActionLayout = null;
// Initialization
this.$element.addClass( 'oo-ui-messageDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.name = 'message';
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.size = 'small';
/**
* @static
* @deprecated since v0.18.4 as default; TODO: Remove
*/
OO.ui.MessageDialog.static.verbose = true;
/**
* Dialog title.
*
* The title of a confirmation dialog describes what a progressive action will do. The
* title of an alert dialog describes which event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.title = null;
/**
* The message displayed in the dialog body.
*
* A confirmation message describes the consequences of a progressive action. An alert
* message describes why an event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.message = null;
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.actions = [
// Note that OO.ui.alert() and OO.ui.confirm() rely on these.
{ action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
{ action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
];
/* Methods */
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
// Events
this.manager.connect( this, {
resize: 'onResize'
} );
return this;
};
/**
* Handle window resized events.
*
* @private
*/
OO.ui.MessageDialog.prototype.onResize = function () {
var dialog = this;
dialog.fitActions();
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.fitActions();
}, 300 );
};
/**
* Toggle action layout between vertical and horizontal.
*
* @private
* @param {boolean} [value] Layout actions vertically, omit to toggle
* @chainable
*/
OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
value = value === undefined ? !this.verticalActionLayout : !!value;
if ( value !== this.verticalActionLayout ) {
this.verticalActionLayout = value;
this.$actions
.toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
.toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
if ( action ) {
return new OO.ui.Process( function () {
this.close( { action: action } );
}, this );
}
return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
* @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
* @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
* action item
*/
OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
this.title.setLabel(
data.title !== undefined ? data.title : this.constructor.static.title
);
this.message.setLabel(
data.message !== undefined ? data.message : this.constructor.static.message
);
// @deprecated since v0.18.4 as default; TODO: Remove and make default instead.
this.message.$element.toggleClass(
'oo-ui-messageDialog-message-verbose',
data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
);
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
.next( function () {
// Focus the primary action button
var actions = this.actions.get();
actions = actions.filter( function ( action ) {
return action.getFlags().indexOf( 'primary' ) > -1;
} );
if ( actions.length > 0 ) {
actions[ 0 ].$button.focus();
}
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getBodyHeight = function () {
var bodyHeight, oldOverflow,
$scrollable = this.container.$element;
oldOverflow = $scrollable[ 0 ].style.overflow;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
bodyHeight = this.text.$element.outerHeight( true );
$scrollable[ 0 ].style.overflow = oldOverflow;
return bodyHeight;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
var $scrollable = this.container.$element;
OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
// Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
// Need to do it after transition completes (250ms), add 50ms just in case.
setTimeout( function () {
var oldOverflow = $scrollable[ 0 ].style.overflow,
activeElement = document.activeElement;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
// Check reconsiderScrollbars didn't destroy our focus, as we
// are doing this after the ready process.
if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
activeElement.focus();
}
$scrollable[ 0 ].style.overflow = oldOverflow;
}, 300 );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.initialize = function () {
// Parent method
OO.ui.MessageDialog.parent.prototype.initialize.call( this );
// Properties
this.$actions = $( '<div>' );
this.container = new OO.ui.PanelLayout( {
scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
} );
this.text = new OO.ui.PanelLayout( {
padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
} );
this.message = new OO.ui.LabelWidget( {
classes: [ 'oo-ui-messageDialog-message' ]
} );
// Initialization
this.title.$element.addClass( 'oo-ui-messageDialog-title' );
this.$content.addClass( 'oo-ui-messageDialog-content' );
this.container.$element.append( this.text.$element );
this.text.$element.append( this.title.$element, this.message.$element );
this.$body.append( this.container.$element );
this.$actions.addClass( 'oo-ui-messageDialog-actions' );
this.$foot.append( this.$actions );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.safe ) {
this.$actions.append( special.safe.$element );
special.safe.toggleFramed( false );
}
if ( others.length ) {
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$actions.append( other.$element );
other.toggleFramed( false );
}
}
if ( special.primary ) {
this.$actions.append( special.primary.$element );
special.primary.toggleFramed( false );
}
if ( !this.isOpening() ) {
// If the dialog is currently opening, this will be called automatically soon.
// This also calls #fitActions.
this.updateSize();
}
};
/**
* Fit action actions into columns or rows.
*
* Columns will be used if all labels can fit without overflow, otherwise rows will be used.
*
* @private
*/
OO.ui.MessageDialog.prototype.fitActions = function () {
var i, len, action,
previous = this.verticalActionLayout,
actions = this.actions.get();
// Detect clipping
this.toggleVerticalActionLayout( false );
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
this.toggleVerticalActionLayout( true );
break;
}
}
// Move the body out of the way of the foot
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
if ( this.verticalActionLayout !== previous ) {
// We changed the layout, window height might need to be updated.
this.updateSize();
}
};
/**
* ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
* to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
* interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
* relevant. The ProcessDialog class is always extended and customized with the actions and content
* required for each process.
*
* The process dialog box consists of a header that visually represents the ‘working’ state of long
* processes with an animation. The header contains the dialog title as well as
* two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
* a ‘primary’ action on the right (e.g., ‘Done’).
*
* Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
* Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
*
* @example
* // Example: Creating and opening a process dialog window.
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
*
* MyProcessDialog.static.name = 'myProcessDialog';
* MyProcessDialog.static.title = 'Process dialog';
* MyProcessDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
* this.$body.append( this.content.$element );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action ) {
* return new OO.ui.Process( function () {
* dialog.close( { action: action } );
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* var dialog = new MyProcessDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
// Parent constructor
OO.ui.ProcessDialog.parent.call( this, config );
// Properties
this.fitOnOpen = false;
// Initialization
this.$element.addClass( 'oo-ui-processDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
/* Methods */
/**
* Handle dismiss button click events.
*
* Hides errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
this.hideErrors();
};
/**
* Handle retry button click events.
*
* Hides errors and then tries again.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
this.hideErrors();
this.executeAction( this.currentAction );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.initialize = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
// Properties
this.$navigation = $( '<div>' );
this.$location = $( '<div>' );
this.$safeActions = $( '<div>' );
this.$primaryActions = $( '<div>' );
this.$otherActions = $( '<div>' );
this.dismissButton = new OO.ui.ButtonWidget( {
label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
} );
this.retryButton = new OO.ui.ButtonWidget();
this.$errors = $( '<div>' );
this.$errorsTitle = $( '<div>' );
// Events
this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
// Initialization
this.title.$element.addClass( 'oo-ui-processDialog-title' );
this.$location
.append( this.title.$element )
.addClass( 'oo-ui-processDialog-location' );
this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
this.$errorsTitle
.addClass( 'oo-ui-processDialog-errors-title' )
.text( OO.ui.msg( 'ooui-dialog-process-error' ) );
this.$errors
.addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
.append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
this.$content
.addClass( 'oo-ui-processDialog-content' )
.append( this.$errors );
this.$navigation
.addClass( 'oo-ui-processDialog-navigation' )
// Note: Order of appends below is important. These are in the order
// we want tab to go through them. Display-order is handled entirely
// by CSS absolute-positioning. As such, primary actions like "done"
// should go first.
.append( this.$primaryActions, this.$location, this.$safeActions );
this.$head.append( this.$navigation );
this.$foot.append( this.$otherActions );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
var i, len, config,
isMobile = OO.ui.isMobile(),
widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
config = $.extend( { framed: !OO.ui.isMobile() }, actions[ i ] );
if ( isMobile &&
( config.flags === 'back' || ( Array.isArray( config.flags ) && config.flags.indexOf( 'back' ) !== -1 ) )
) {
$.extend( config, {
icon: 'previous',
label: ''
} );
}
widgets.push(
new OO.ui.ActionWidget( config )
);
}
return widgets;
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.primary ) {
this.$primaryActions.append( special.primary.$element );
}
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$otherActions.append( other.$element );
}
if ( special.safe ) {
this.$safeActions.append( special.safe.$element );
}
this.fitLabel();
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
var process = this;
return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
.fail( function ( errors ) {
process.showErrors( errors || [] );
} );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.setDimensions = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
this.fitLabel();
};
/**
* Fit label between actions.
*
* @private
* @chainable
*/
OO.ui.ProcessDialog.prototype.fitLabel = function () {
var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
size = this.getSizeProperties();
if ( typeof size.width !== 'number' ) {
if ( this.isOpened() ) {
navigationWidth = this.$head.width() - 20;
} else if ( this.isOpening() ) {
if ( !this.fitOnOpen ) {
// Size is relative and the dialog isn't open yet, so wait.
this.manager.opening.done( this.fitLabel.bind( this ) );
this.fitOnOpen = true;
}
return;
} else {
return;
}
} else {
navigationWidth = size.width - 20;
}
safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
biggerWidth = Math.max( safeWidth, primaryWidth );
labelWidth = this.title.$element.width();
if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
// We have enough space to center the label
leftWidth = rightWidth = biggerWidth;
} else {
// Let's hope we at least have enough space not to overlap, because we can't wrap the label…
if ( this.getDir() === 'ltr' ) {
leftWidth = safeWidth;
rightWidth = primaryWidth;
} else {
leftWidth = primaryWidth;
rightWidth = safeWidth;
}
}
this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
return this;
};
/**
* Handle errors that occurred during accept or reject processes.
*
* @private
* @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
*/
OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
var i, len, $item, actions,
items = [],
abilities = {},
recoverable = true,
warning = false;
if ( errors instanceof OO.ui.Error ) {
errors = [ errors ];
}
for ( i = 0, len = errors.length; i < len; i++ ) {
if ( !errors[ i ].isRecoverable() ) {
recoverable = false;
}
if ( errors[ i ].isWarning() ) {
warning = true;
}
$item = $( '<div>' )
.addClass( 'oo-ui-processDialog-error' )
.append( errors[ i ].getMessage() );
items.push( $item[ 0 ] );
}
this.$errorItems = $( items );
if ( recoverable ) {
abilities[ this.currentAction ] = true;
// Copy the flags from the first matching action
actions = this.actions.get( { actions: this.currentAction } );
if ( actions.length ) {
this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
}
} else {
abilities[ this.currentAction ] = false;
this.actions.setAbilities( abilities );
}
if ( warning ) {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
} else {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
}
this.retryButton.toggle( recoverable );
this.$errorsTitle.after( this.$errorItems );
this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
};
/**
* Hide errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.hideErrors = function () {
this.$errors.addClass( 'oo-ui-element-hidden' );
if ( this.$errorItems ) {
this.$errorItems.remove();
this.$errorItems = null;
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
// Make sure to hide errors
this.hideErrors();
this.fitOnOpen = false;
}, this );
};
/**
* @class OO.ui
*/
/**
* Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
* OO.ui.confirm.
*
* @private
* @return {OO.ui.WindowManager}
*/
OO.ui.getWindowManager = function () {
if ( !OO.ui.windowManager ) {
OO.ui.windowManager = new OO.ui.WindowManager();
$( 'body' ).append( OO.ui.windowManager.$element );
OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
}
return OO.ui.windowManager;
};
/**
* Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
* rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
* has only one action button, labelled "OK", clicking it will simply close the dialog.
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.alert( 'Something happened!' ).done( function () {
* console.log( 'User closed the dialog.' );
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog
*/
OO.ui.alert = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text,
actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
}, options ) ).then( function ( opened ) {
return opened.then( function ( closing ) {
return closing.then( function () {
return $.Deferred().resolve();
} );
} );
} );
};
/**
* Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
* (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
* if ( confirmed ) {
* console.log( 'User clicked "OK"!' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
* `false`.
*/
OO.ui.confirm = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text
}, options ) ).then( function ( opened ) {
return opened.then( function ( closing ) {
return closing.then( function ( data ) {
return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
} );
} );
} );
};
/**
* Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has a text input widget and two action buttons, one to confirm an operation (labelled "OK")
* and one to cancel it (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.prompt( 'Choose a line to go to', { textInput: { placeholder: 'Line number' } } ).done( function ( result ) {
* if ( result !== null ) {
* console.log( 'User typed "' + result + '" then clicked "OK".' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @param {Object} [options.textInput] Additional options for text input widget, see OO.ui.TextInputWidget
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve with the value of the text input widget; otherwise, it will
* resolve to `null`.
*/
OO.ui.prompt = function ( text, options ) {
var manager = OO.ui.getWindowManager(),
textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
textField = new OO.ui.FieldLayout( textInput, {
align: 'top',
label: text
} );
// TODO: This is a little hacky, and could be done by extending MessageDialog instead.
return manager.openWindow( 'message', $.extend( {
message: textField.$element
}, options ) ).then( function ( opened ) {
// After ready
textInput.on( 'enter', function () {
manager.getCurrentWindow().close( { action: 'accept' } );
} );
textInput.focus();
return opened.then( function ( closing ) {
return closing.then( function ( data ) {
return $.Deferred().resolve( data && data.action === 'accept' ? textInput.getValue() : null );
} );
} );
} );
};
}( OO ) );
|
project-structure/src/banner/bannerContainer.js | shariati/learn-react | import React, { Component } from 'react';
import BannerComponent from './bannerComponent';
import APIServices from '../service/apiService'
export default class BannerContainer extends Component {
constructor() {
super()
this.state = {
movies : []
}
}
componentWillMount() {
APIServices.getBanner().then((response)=>{
this.setState({
movies : response.data.Search
})
}).catch((error)=>{
console.log(error)
})
}
render() {
return (
<BannerComponent {...this.state}/>
);
}
}
|
__tests__/js/scenes/Profile.js | arcturus/journey | import 'react-native';
import React from 'react';
import { Profile } from '../../../js/scenes/Profile';
import renderer from 'react-test-renderer';
jest.mock('../../../js/components/Header', () => 'Header');
it('renders correctly', () => {
const tree = renderer.create(
<Profile/>
);
});
|
src/routes/home/Home.js | chaudhryjunaid/chaudhryjunaid.com | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-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 React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Home.css';
class Home extends React.Component {
static propTypes = {
news: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
content: PropTypes.string,
}),
).isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>React.js News</h1>
{this.props.news.map(item => (
<article key={item.link} className={s.newsItem}>
<h1 className={s.newsTitle}>
<a href={item.link}>{item.title}</a>
</h1>
<div
className={s.newsDesc}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: item.content }}
/>
</article>
))}
</div>
</div>
);
}
}
export default withStyles(s)(Home);
|
public/javascripts/react-addons-css-transition-group.js | dgynn/canvas-lms | define(['react'], function(React) {
return React.ReactCSSTransitionGroup;
});
|
packages/material-ui-icons/src/RecentActors.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let RecentActors = props =>
<SvgIcon {...props}>
<path d="M21 5v14h2V5h-2zm-4 14h2V5h-2v14zM14 5H2c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM8 7.75c1.24 0 2.25 1.01 2.25 2.25S9.24 12.25 8 12.25 5.75 11.24 5.75 10 6.76 7.75 8 7.75zM12.5 17h-9v-.75c0-1.5 3-2.25 4.5-2.25s4.5.75 4.5 2.25V17z" />
</SvgIcon>;
RecentActors = pure(RecentActors);
RecentActors.muiName = 'SvgIcon';
export default RecentActors;
|
ajax/libs/yui/3.8.0pr1/event-focus/event-focus.js | xymostech/cdnjs | YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var p = Y.config.doc.createElement("p"),
listener;
p.setAttribute("onbeforeactivate", ";");
listener = p.onbeforeactivate;
// listener is a function in IE8+.
// listener is a string in IE6,7 (unfortunate, but that's not going to change. Otherwise we could have just checked for function).
// listener is a function in IE10, in a Win8 App environment (no exception running the test).
// listener is undefined in Webkit/Gecko.
// listener is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
return (listener !== undefined);
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@', {"requires": ["event-synthetic"]});
|
docs/src/app/components/pages/components/IconButton/ExampleSimple.js | pomerantsev/material-ui | import React from 'react';
import IconButton from 'material-ui/IconButton';
const IconButtonExampleSimple = () => (
<div>
<IconButton iconClassName="muidocs-icon-custom-github" />
<IconButton iconClassName="muidocs-icon-custom-github" disabled={true} />
</div>
);
export default IconButtonExampleSimple;
|
src/svg-icons/device/sd-storage.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSdStorage = (props) => (
<SvgIcon {...props}>
<path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 6h-2V4h2v4zm3 0h-2V4h2v4zm3 0h-2V4h2v4z"/>
</SvgIcon>
);
DeviceSdStorage = pure(DeviceSdStorage);
DeviceSdStorage.displayName = 'DeviceSdStorage';
DeviceSdStorage.muiName = 'SvgIcon';
export default DeviceSdStorage;
|
src/createMatchMediaConnect.js | malte-wessel/react-matchmedia-connect | import React, { Component } from 'react';
import shallowEqual from 'shallowequal';
import throttle from './utils/throttle';
import pick from './utils/pick';
function pickState(pickProperties, stateToPickFrom) {
if (!pickProperties.length) return stateToPickFrom;
return pick(stateToPickFrom, ...pickProperties);
}
export default function createMatchMediaConnect(queryMap = {}, options = {}) {
const { matchMediaFn = window.matchMedia } = options;
const mqls = {};
const listeners = [];
let state = {};
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
function createState() {
const nextState = {};
for (const key in mqls) {
if (!mqls.hasOwnProperty(key)) continue;
const mql = mqls[key];
const { matches } = mql;
nextState[key] = matches;
}
return nextState;
}
const handleChange = throttle(() => {
const nextState = createState();
if (shallowEqual(state, nextState)) return;
state = nextState;
for (let i = 0, l = listeners.length; i < l; i++) {
const listener = listeners[i];
if (!listener) continue;
listener(nextState);
}
});
if (matchMediaFn) {
for (const key in queryMap) {
if (!queryMap.hasOwnProperty(key)) continue;
const query = queryMap[key];
const mql = matchMediaFn(query);
mql.addListener(handleChange);
mqls[key] = mql;
}
}
function destroy() {
listeners.length = 0;
for (const key in mqls) {
if (!mqls.hasOwnProperty(key)) continue;
const mql = mqls[key];
mql.removeListener(handleChange);
mqls[key] = undefined;
}
}
state = createState();
function connect(pickProperties = []) {
return function wrapWithConnect(WrappedComponent) {
return class WrapWithConnect extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = pickState(pickProperties, state);
}
componentDidMount() {
this.unsubscribe = subscribe(this.handleChange);
}
componentWillUnmount() {
this.unsubscribe();
}
handleChange(nextState) {
const nextPickedState = pickState(
pickProperties,
nextState
);
if (shallowEqual(this.state, nextPickedState)) {
return;
}
this.setState(nextPickedState);
}
render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
};
}
// For testing
connect.destroy = destroy;
connect.listeners = listeners;
return connect;
}
|
dispatch/static/manager/src/js/components/inputs/ConfirmButton.js | ubyssey/dispatch | import React from 'react'
import { Button, Alert, Intent } from '@blueprintjs/core'
export default class ConfirmButton extends React.Component {
constructor(props) {
super(props)
this.state = {
alertOpen: false
}
}
onConfirm() {
this.setState({alertOpen: false}, () => {
this.props.onConfirm()
})
}
render() {
return (
<Button
className={this.props.className}
intent={this.props.intent}
icon={this.props.icon}
disabled={this.props.disabled}
onClick={() => this.setState({ alertOpen: true })}>
{this.props.children}
<Alert
isOpen={this.state.alertOpen}
cancelButtonText='Cancel'
confirmButtonText={this.props.confirmButtonText}
iconName='trash'
onCancel={() => this.setState({ alertOpen: false })}
onConfirm={() => this.onConfirm()}
intent={Intent.DANGER}>
<p>{this.props.message}</p>
</Alert>
</Button>
)
}
}
ConfirmButton.defaultProps = {
message: 'Are you sure you want to delete this?',
confirmButtonText: 'Delete'
}
|
src/Badge.js | chrishoage/react-bootstrap | import React from 'react';
import ValidComponentChildren from './utils/ValidComponentChildren';
import classNames from 'classnames';
const Badge = React.createClass({
propTypes: {
pullRight: React.PropTypes.bool
},
getDefaultProps() {
return {
pullRight: false
};
},
hasContent() {
return ValidComponentChildren.hasValidComponent(this.props.children) ||
(React.Children.count(this.props.children) > 1) ||
(typeof this.props.children === 'string') ||
(typeof this.props.children === 'number');
},
render() {
let classes = {
'pull-right': this.props.pullRight,
'badge': this.hasContent()
};
return (
<span
{...this.props}
className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Badge;
|
ajax/libs/video.js/5.4.2/alt/video.novtt.js | dakshshah96/cdnjs | /**
* @license
* Video.js 5.4.2 <http://videojs.com/>
* Copyright Brightcove, Inc. <https://www.brightcove.com/>
* Available under Apache License Version 2.0
* <https://github.com/videojs/video.js/blob/master/LICENSE>
*/
(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.videojs = 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){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = _dereq_('min-document');
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19
},{"min-document":3}],2:[function(_dereq_,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19
},{}],3:[function(_dereq_,module,exports){
},{}],4:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeNow = getNative(Date, 'now');
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
module.exports = now;
},{"../internal/getNative":20}],5:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
now = _dereq_('../date/now');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the debounced function return the result of the last
* `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it's invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = !!options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
if (id) {
clearTimeout(id);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
}
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
complete(trailingCall, maxTimeoutId);
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
complete(trailing, timeoutId);
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
module.exports = debounce;
},{"../date/now":4,"../lang/isObject":33}],6:[function(_dereq_,module,exports){
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],7:[function(_dereq_,module,exports){
var debounce = _dereq_('./debounce'),
isObject = _dereq_('../lang/isObject');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed invocations. Provide an options object to indicate
* that `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. Subsequent calls to the throttled function return the
* result of the last `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
}
module.exports = throttle;
},{"../lang/isObject":33,"./debounce":5}],8:[function(_dereq_,module,exports){
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = arrayCopy;
},{}],9:[function(_dereq_,module,exports){
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
},{}],10:[function(_dereq_,module,exports){
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],11:[function(_dereq_,module,exports){
var createBaseFor = _dereq_('./createBaseFor');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
},{"./createBaseFor":18}],12:[function(_dereq_,module,exports){
var baseFor = _dereq_('./baseFor'),
keysIn = _dereq_('../object/keysIn');
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
module.exports = baseForIn;
},{"../object/keysIn":39,"./baseFor":11}],13:[function(_dereq_,module,exports){
var arrayEach = _dereq_('./arrayEach'),
baseMergeDeep = _dereq_('./baseMergeDeep'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isObject = _dereq_('../lang/isObject'),
isObjectLike = _dereq_('./isObjectLike'),
isTypedArray = _dereq_('../lang/isTypedArray'),
keys = _dereq_('../object/keys');
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns `object`.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
props = isSrcArr ? undefined : keys(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
else {
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
}
if ((result !== undefined || (isSrcArr && !(key in object))) &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
}
});
return object;
}
module.exports = baseMerge;
},{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":9,"./baseMergeDeep":14,"./isArrayLike":21,"./isObjectLike":26}],14:[function(_dereq_,module,exports){
var arrayCopy = _dereq_('./arrayCopy'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isPlainObject = _dereq_('../lang/isPlainObject'),
isTypedArray = _dereq_('../lang/isTypedArray'),
toPlainObject = _dereq_('../lang/toPlainObject');
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: (isArrayLike(value) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
module.exports = baseMergeDeep;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":8,"./isArrayLike":21}],15:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : toObject(object)[key];
};
}
module.exports = baseProperty;
},{"./toObject":28}],16:[function(_dereq_,module,exports){
var identity = _dereq_('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":42}],17:[function(_dereq_,module,exports){
var bindCallback = _dereq_('./bindCallback'),
isIterateeCall = _dereq_('./isIterateeCall'),
restParam = _dereq_('../function/restParam');
/**
* Creates a `_.assign`, `_.defaults`, or `_.merge` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"../function/restParam":6,"./bindCallback":16,"./isIterateeCall":24}],18:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
},{"./toObject":28}],19:[function(_dereq_,module,exports){
var baseProperty = _dereq_('./baseProperty');
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
module.exports = getLength;
},{"./baseProperty":15}],20:[function(_dereq_,module,exports){
var isNative = _dereq_('../lang/isNative');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
module.exports = getNative;
},{"../lang/isNative":32}],21:[function(_dereq_,module,exports){
var getLength = _dereq_('./getLength'),
isLength = _dereq_('./isLength');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
module.exports = isArrayLike;
},{"./getLength":19,"./isLength":25}],22:[function(_dereq_,module,exports){
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
// IE < 9 presents many host objects as `Object` objects that can coerce
// to strings despite having improperly defined `toString` methods.
return typeof value.toString != 'function' && typeof (value + '') == 'string';
};
}());
module.exports = isHostObject;
},{}],23:[function(_dereq_,module,exports){
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],24:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('./isArrayLike'),
isIndex = _dereq_('./isIndex'),
isObject = _dereq_('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":33,"./isArrayLike":21,"./isIndex":23}],25:[function(_dereq_,module,exports){
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],26:[function(_dereq_,module,exports){
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],27:[function(_dereq_,module,exports){
var isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isIndex = _dereq_('./isIndex'),
isLength = _dereq_('./isLength'),
isString = _dereq_('../lang/isString'),
keysIn = _dereq_('../object/keysIn');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":23,"./isLength":25}],28:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
if (support.unindexedChars && isString(value)) {
var index = -1,
length = value.length,
result = Object(value);
while (++index < length) {
result[index] = value.charAt(index);
}
return result;
}
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":33,"../lang/isString":35,"../support":41}],29:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('../internal/isArrayLike'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
},{"../internal/isArrayLike":21,"../internal/isObjectLike":26}],30:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
module.exports = isArray;
},{"../internal/getNative":20,"../internal/isLength":25,"../internal/isObjectLike":26}],31:[function(_dereq_,module,exports){
var isObject = _dereq_('./isObject');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 which returns 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
module.exports = isFunction;
},{"./isObject":33}],32:[function(_dereq_,module,exports){
var isFunction = _dereq_('./isFunction'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
}
module.exports = isNative;
},{"../internal/isHostObject":22,"../internal/isObjectLike":26,"./isFunction":31}],33:[function(_dereq_,module,exports){
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],34:[function(_dereq_,module,exports){
var baseForIn = _dereq_('../internal/baseForIn'),
isArguments = _dereq_('./isArguments'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
var Ctor;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) ||
(!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
if (support.ownLast) {
baseForIn(value, function(subValue, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return result === undefined || hasOwnProperty.call(value, result);
}
module.exports = isPlainObject;
},{"../internal/baseForIn":12,"../internal/isHostObject":22,"../internal/isObjectLike":26,"../support":41,"./isArguments":29}],35:[function(_dereq_,module,exports){
var isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
},{"../internal/isObjectLike":26}],36:[function(_dereq_,module,exports){
var isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
},{"../internal/isLength":25,"../internal/isObjectLike":26}],37:[function(_dereq_,module,exports){
var baseCopy = _dereq_('../internal/baseCopy'),
keysIn = _dereq_('../object/keysIn');
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
module.exports = toPlainObject;
},{"../internal/baseCopy":10,"../object/keysIn":39}],38:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isArrayLike = _dereq_('../internal/isArrayLike'),
isObject = _dereq_('../lang/isObject'),
shimKeys = _dereq_('../internal/shimKeys'),
support = _dereq_('../support');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/getNative":20,"../internal/isArrayLike":21,"../internal/shimKeys":27,"../lang/isObject":33,"../support":41}],39:[function(_dereq_,module,exports){
var arrayEach = _dereq_('../internal/arrayEach'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isFunction = _dereq_('../lang/isFunction'),
isIndex = _dereq_('../internal/isIndex'),
isLength = _dereq_('../internal/isLength'),
isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/** Used to fix the JScript `[[DontEnum]]` bug. */
var shadowProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used for native method references. */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to avoid iterating over non-enumerable properties in IE < 9. */
var nonEnumProps = {};
nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true };
nonEnumProps[objectTag] = { 'constructor': true };
arrayEach(shadowProps, function(key) {
for (var tag in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, tag)) {
var props = nonEnumProps[tag];
props[key] = hasOwnProperty.call(props, key);
}
}
});
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
proto = (isFunction(Ctor) && Ctor.prototype) || objectProto,
isProto = proto === object,
result = Array(length),
skipIndexes = length > 0,
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error),
skipProto = support.enumPrototypes && isFunction(object);
while (++index < length) {
result[index] = (index + '');
}
// lodash skips the `constructor` property when it infers it's iterating
// over a `prototype` object because IE < 9 can't set the `[[Enumerable]]`
// attribute of an existing property and the `constructor` property of a
// prototype defaults to non-enumerable.
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name')) &&
!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)),
nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag];
if (tag == objectTag) {
proto = objectProto;
}
length = shadowProps.length;
while (length--) {
key = shadowProps[length];
var nonEnum = nonEnums[key];
if (!(isProto && nonEnum) &&
(nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) {
result.push(key);
}
}
}
return result;
}
module.exports = keysIn;
},{"../internal/arrayEach":9,"../internal/isIndex":23,"../internal/isLength":25,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":41}],40:[function(_dereq_,module,exports){
var baseMerge = _dereq_('../internal/baseMerge'),
createAssigner = _dereq_('../internal/createAssigner');
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it's invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
module.exports = merge;
},{"../internal/baseMerge":13,"../internal/createAssigner":17}],41:[function(_dereq_,module,exports){
/** Used for native method references. */
var arrayProto = Array.prototype,
errorProto = Error.prototype,
objectProto = Object.prototype;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = {};
(function(x) {
var Ctor = function() { this.x = x; },
object = { '0': x, 'length': x },
props = [];
Ctor.prototype = { 'valueOf': x, 'y': x };
for (var key in new Ctor) { props.push(key); }
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default (IE < 9, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') ||
propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly set the `[[Enumerable]]` value of a function's `prototype`
* property to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype');
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an object's own properties, shadowing non-enumerable ones,
* are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects
* correctly.
*
* Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array
* `shift()` and `splice()` functions that fail to remove the last element,
* `value[0]`, of array-like objects even though the "length" property is
* set to `0`. The `shift()` method is buggy in compatibility modes of IE 8,
* while `splice()` is buggy regardless of mode in IE < 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index. IE 8 can only access characters
* by index on string literals, not string objects.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
}(1, 0));
module.exports = support;
},{}],42:[function(_dereq_,module,exports){
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
},{}],43:[function(_dereq_,module,exports){
'use strict';
var keys = _dereq_('object-keys');
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
if (typeof sym === 'string') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(Object(sym) instanceof Symbol)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; }
if (keys(obj).length !== 0) { return false; }
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
},{"object-keys":49}],44:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es6-shim
var keys = _dereq_('object-keys');
var bind = _dereq_('function-bind');
var canBeObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var hasSymbols = _dereq_('./hasSymbols')();
var toObject = Object;
var push = bind.call(Function.call, Array.prototype.push);
var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);
module.exports = function assign(target, source1) {
if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
var objTarget = toObject(target);
var s, source, i, props, syms, value, key;
for (s = 1; s < arguments.length; ++s) {
source = toObject(arguments[s]);
props = keys(source);
if (hasSymbols && Object.getOwnPropertySymbols) {
syms = Object.getOwnPropertySymbols(source);
for (i = 0; i < syms.length; ++i) {
key = syms[i];
if (propIsEnumerable(source, key)) {
push(props, key);
}
}
}
for (i = 0; i < props.length; ++i) {
key = props[i];
value = source[key];
if (propIsEnumerable(source, key)) {
objTarget[key] = value;
}
}
}
return objTarget;
};
},{"./hasSymbols":43,"function-bind":48,"object-keys":49}],45:[function(_dereq_,module,exports){
'use strict';
var defineProperties = _dereq_('define-properties');
var implementation = _dereq_('./implementation');
var getPolyfill = _dereq_('./polyfill');
var shim = _dereq_('./shim');
defineProperties(implementation, {
implementation: implementation,
getPolyfill: getPolyfill,
shim: shim
});
module.exports = implementation;
},{"./implementation":44,"./polyfill":51,"./shim":52,"define-properties":46}],46:[function(_dereq_,module,exports){
'use strict';
var keys = _dereq_('object-keys');
var foreach = _dereq_('foreach');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
var toStr = Object.prototype.toString;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
/* eslint-disable no-unused-vars, no-restricted-syntax */
for (var _ in obj) { return false; }
/* eslint-enable no-unused-vars, no-restricted-syntax */
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = props.concat(Object.getOwnPropertySymbols(map));
}
foreach(props, function (name) {
defineProperty(object, name, map[name], predicates[name]);
});
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
},{"foreach":47,"object-keys":49}],47:[function(_dereq_,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);
}
}
}
};
},{}],48:[function(_dereq_,module,exports){
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
var bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
},{}],49:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = _dereq_('./isArguments');
var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var blacklistedKeys = {
$console: true,
$frame: true,
$frameElement: true,
$frames: true,
$parent: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"./isArguments":50}],50:[function(_dereq_,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],51:[function(_dereq_,module,exports){
'use strict';
var implementation = _dereq_('./implementation');
var lacksProperEnumerationOrder = function () {
if (!Object.assign) {
return false;
}
// v8, specifically in node 4.x, has a bug with incorrect property enumeration order
// note: this does not detect the bug unless there's 20 characters
var str = 'abcdefghijklmnopqrst';
var letters = str.split('');
var map = {};
for (var i = 0; i < letters.length; ++i) {
map[letters[i]] = letters[i];
}
var obj = Object.assign({}, map);
var actual = '';
for (var k in obj) {
actual += k;
}
return str !== actual;
};
var assignHasPendingExceptions = function () {
if (!Object.assign || !Object.preventExtensions) {
return false;
}
// Firefox 37 still has "pending exception" logic in its Object.assign implementation,
// which is 72% slower than our shim, and Firefox 40's native implementation.
var thrower = Object.preventExtensions({ 1: 2 });
try {
Object.assign(thrower, 'xy');
} catch (e) {
return thrower[1] === 'y';
}
};
module.exports = function getPolyfill() {
if (!Object.assign) {
return implementation;
}
if (lacksProperEnumerationOrder()) {
return implementation;
}
if (assignHasPendingExceptions()) {
return implementation;
}
return Object.assign;
};
},{"./implementation":44}],52:[function(_dereq_,module,exports){
'use strict';
var define = _dereq_('define-properties');
var getPolyfill = _dereq_('./polyfill');
module.exports = function shimAssign() {
var polyfill = getPolyfill();
define(
Object,
{ assign: polyfill },
{ assign: function () { return Object.assign !== polyfill; } }
);
return polyfill;
};
},{"./polyfill":51,"define-properties":46}],53:[function(_dereq_,module,exports){
module.exports = SafeParseTuple
function SafeParseTuple(obj, reviver) {
var json
var error = null
try {
json = JSON.parse(obj, reviver)
} catch (err) {
error = err
}
return [error, json]
}
},{}],54:[function(_dereq_,module,exports){
function clean (s) {
return s.replace(/\n\r?\s*/g, '')
}
module.exports = function tsml (sa) {
var s = ''
, i = 0
for (; i < arguments.length; i++)
s += clean(sa[i]) + (arguments[i + 1] || '')
return s
}
},{}],55:[function(_dereq_,module,exports){
"use strict";
var window = _dereq_("global/window")
var once = _dereq_("once")
var isFunction = _dereq_("is-function")
var parseHeaders = _dereq_("parse-headers")
var xtend = _dereq_("xtend")
module.exports = createXHR
createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
options = initParams(uri, options, callback)
options.method = method.toUpperCase()
return _createXHR(options)
}
})
function forEachArray(array, iterator) {
for (var i = 0; i < array.length; i++) {
iterator(array[i])
}
}
function isEmpty(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)) return false
}
return true
}
function initParams(uri, options, callback) {
var params = uri
if (isFunction(options)) {
callback = options
if (typeof uri === "string") {
params = {uri:uri}
}
} else {
params = xtend(options, {uri: uri})
}
params.callback = callback
return params
}
function createXHR(uri, options, callback) {
options = initParams(uri, options, callback)
return _createXHR(options)
}
function _createXHR(options) {
var callback = options.callback
if(typeof callback === "undefined"){
throw new Error("callback argument missing")
}
callback = once(callback)
function readystatechange() {
if (xhr.readyState === 4) {
loadFunc()
}
}
function getBody() {
// Chrome with requestType=blob throws errors arround when even testing access to responseText
var body = undefined
if (xhr.response) {
body = xhr.response
} else if (xhr.responseType === "text" || !xhr.responseType) {
body = xhr.responseText || xhr.responseXML
}
if (isJson) {
try {
body = JSON.parse(body)
} catch (e) {}
}
return body
}
var failureResponse = {
body: undefined,
headers: {},
statusCode: 0,
method: method,
url: uri,
rawRequest: xhr
}
function errorFunc(evt) {
clearTimeout(timeoutTimer)
if(!(evt instanceof Error)){
evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
}
evt.statusCode = 0
callback(evt, failureResponse)
}
// will load the data & process the response in a special response object
function loadFunc() {
if (aborted) return
var status
clearTimeout(timeoutTimer)
if(options.useXDR && xhr.status===undefined) {
//IE8 CORS GET successful response doesn't have a status field, but body is fine
status = 200
} else {
status = (xhr.status === 1223 ? 204 : xhr.status)
}
var response = failureResponse
var err = null
if (status !== 0){
response = {
body: getBody(),
statusCode: status,
method: method,
headers: {},
url: uri,
rawRequest: xhr
}
if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
response.headers = parseHeaders(xhr.getAllResponseHeaders())
}
} else {
err = new Error("Internal XMLHttpRequest Error")
}
callback(err, response, response.body)
}
var xhr = options.xhr || null
if (!xhr) {
if (options.cors || options.useXDR) {
xhr = new createXHR.XDomainRequest()
}else{
xhr = new createXHR.XMLHttpRequest()
}
}
var key
var aborted
var uri = xhr.url = options.uri || options.url
var method = xhr.method = options.method || "GET"
var body = options.body || options.data || null
var headers = xhr.headers = options.headers || {}
var sync = !!options.sync
var isJson = false
var timeoutTimer
if ("json" in options) {
isJson = true
headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
if (method !== "GET" && method !== "HEAD") {
headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
body = JSON.stringify(options.json)
}
}
xhr.onreadystatechange = readystatechange
xhr.onload = loadFunc
xhr.onerror = errorFunc
// IE9 must have onprogress be set to a unique function.
xhr.onprogress = function () {
// IE must die
}
xhr.ontimeout = errorFunc
xhr.open(method, uri, !sync, options.username, options.password)
//has to be after open
if(!sync) {
xhr.withCredentials = !!options.withCredentials
}
// Cannot set timeout with sync request
// not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
// both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
if (!sync && options.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
aborted=true//IE9 may still call readystatechange
xhr.abort("timeout")
var e = new Error("XMLHttpRequest timeout")
e.code = "ETIMEDOUT"
errorFunc(e)
}, options.timeout )
}
if (xhr.setRequestHeader) {
for(key in headers){
if(headers.hasOwnProperty(key)){
xhr.setRequestHeader(key, headers[key])
}
}
} else if (options.headers && !isEmpty(options.headers)) {
throw new Error("Headers cannot be set on an XDomainRequest object")
}
if ("responseType" in options) {
xhr.responseType = options.responseType
}
if ("beforeSend" in options &&
typeof options.beforeSend === "function"
) {
options.beforeSend(xhr)
}
xhr.send(body)
return xhr
}
function noop() {}
},{"global/window":2,"is-function":56,"once":57,"parse-headers":60,"xtend":61}],56:[function(_dereq_,module,exports){
module.exports = isFunction
var toString = Object.prototype.toString
function isFunction (fn) {
var string = toString.call(fn)
return string === '[object Function]' ||
(typeof fn === 'function' && string !== '[object RegExp]') ||
(typeof window !== 'undefined' &&
// IE8 and below
(fn === window.setTimeout ||
fn === window.alert ||
fn === window.confirm ||
fn === window.prompt))
};
},{}],57:[function(_dereq_,module,exports){
module.exports = once
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var called = false
return function () {
if (called) return
called = true
return fn.apply(this, arguments)
}
}
},{}],58:[function(_dereq_,module,exports){
var isFunction = _dereq_('is-function')
module.exports = forEach
var toString = Object.prototype.toString
var hasOwnProperty = Object.prototype.hasOwnProperty
function forEach(list, iterator, context) {
if (!isFunction(iterator)) {
throw new TypeError('iterator must be a function')
}
if (arguments.length < 3) {
context = this
}
if (toString.call(list) === '[object Array]')
forEachArray(list, iterator, context)
else if (typeof list === 'string')
forEachString(list, iterator, context)
else
forEachObject(list, iterator, context)
}
function forEachArray(array, iterator, context) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
iterator.call(context, array[i], i, array)
}
}
}
function forEachString(string, iterator, context) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
iterator.call(context, string.charAt(i), i, string)
}
}
function forEachObject(object, iterator, context) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
iterator.call(context, object[k], k, object)
}
}
}
},{"is-function":56}],59:[function(_dereq_,module,exports){
exports = module.exports = trim;
function trim(str){
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
return str.replace(/^\s*/, '');
};
exports.right = function(str){
return str.replace(/\s*$/, '');
};
},{}],60:[function(_dereq_,module,exports){
var trim = _dereq_('trim')
, forEach = _dereq_('for-each')
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
module.exports = function (headers) {
if (!headers)
return {}
var result = {}
forEach(
trim(headers).split('\n')
, function (row) {
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1))
if (typeof(result[key]) === 'undefined') {
result[key] = value
} else if (isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [ result[key], value ]
}
}
)
return result
}
},{"for-each":58,"trim":59}],61:[function(_dereq_,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],62:[function(_dereq_,module,exports){
/**
* @file big-play-button.js
*/
'use strict';
exports.__esModule = true;
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 _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Initial play button. Shows before the video has played. The hiding of the
* big play button is done via CSS and player states.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Button
* @class BigPlayButton
*/
var BigPlayButton = (function (_Button) {
_inherits(BigPlayButton, _Button);
function BigPlayButton(player, options) {
_classCallCheck(this, BigPlayButton);
_Button.call(this, player, options);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
BigPlayButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-big-play-button';
};
/**
* Handles click for play
*
* @method handleClick
*/
BigPlayButton.prototype.handleClick = function handleClick() {
this.player_.play();
};
return BigPlayButton;
})(_buttonJs2['default']);
BigPlayButton.prototype.controlText_ = 'Play Video';
_componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton);
exports['default'] = BigPlayButton;
module.exports = exports['default'];
},{"./button.js":63,"./component.js":65}],63:[function(_dereq_,module,exports){
/**
* @file button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Base class for all buttons
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class Button
*/
var Button = (function (_Component) {
_inherits(Button, _Component);
function Button(player, options) {
_classCallCheck(this, Button);
_Component.call(this, player, options);
this.emitTapEvents();
this.on('tap', this.handleClick);
this.on('click', this.handleClick);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
}
/**
* Create the component's DOM element
*
* @param {String=} type Element's node type. e.g. 'div'
* @param {Object=} props An object of element attributes that should be set on the element Tag name
* @return {Element}
* @method createEl
*/
Button.prototype.createEl = function createEl() {
var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0];
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
props = _objectAssign2['default']({
className: this.buildCSSClass(),
tabIndex: 0
}, props);
// Add standard Aria info
attributes = _objectAssign2['default']({
role: 'button',
type: 'button', // Necessary since the default button type is "submit"
'aria-live': 'polite' // let the screen reader user know that the text of the button may change
}, attributes);
var el = _Component.prototype.createEl.call(this, tag, props, attributes);
this.controlTextEl_ = Dom.createEl('span', {
className: 'vjs-control-text'
});
el.appendChild(this.controlTextEl_);
this.controlText(this.controlText_);
return el;
};
/**
* Controls text - both request and localize
*
* @param {String} text Text for button
* @return {String}
* @method controlText
*/
Button.prototype.controlText = function controlText(text) {
if (!text) return this.controlText_ || 'Need Text';
this.controlText_ = text;
this.controlTextEl_.innerHTML = this.localize(this.controlText_);
return this;
};
/**
* Allows sub components to stack CSS class names
*
* @return {String}
* @method buildCSSClass
*/
Button.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Handle Click - Override with specific functionality for button
*
* @method handleClick
*/
Button.prototype.handleClick = function handleClick() {};
/**
* Handle Focus - Add keyboard functionality to element
*
* @method handleFocus
*/
Button.prototype.handleFocus = function handleFocus() {
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
/**
* Handle KeyPress (document level) - Trigger click when keys are pressed
*
* @method handleKeyPress
*/
Button.prototype.handleKeyPress = function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.handleClick(event);
}
};
/**
* Handle Blur - Remove keyboard triggers
*
* @method handleBlur
*/
Button.prototype.handleBlur = function handleBlur() {
Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
return Button;
})(_component2['default']);
_component2['default'].registerComponent('Button', Button);
exports['default'] = Button;
module.exports = exports['default'];
},{"./component":65,"./utils/dom.js":128,"./utils/events.js":129,"./utils/fn.js":130,"global/document":1,"object.assign":45}],64:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
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 _button = _dereq_('./button');
var _button2 = _interopRequireDefault(_button);
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
/**
* The `CloseButton` component is a button which fires a "close" event
* when it is activated.
*
* @extends Button
* @class CloseButton
*/
var CloseButton = (function (_Button) {
_inherits(CloseButton, _Button);
function CloseButton(player, options) {
_classCallCheck(this, CloseButton);
_Button.call(this, player, options);
this.controlText(options && options.controlText || this.localize('Close'));
}
CloseButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-close-button ' + _Button.prototype.buildCSSClass.call(this);
};
CloseButton.prototype.handleClick = function handleClick() {
this.trigger({ type: 'close', bubbles: false });
};
return CloseButton;
})(_button2['default']);
_component2['default'].registerComponent('CloseButton', CloseButton);
exports['default'] = CloseButton;
module.exports = exports['default'];
},{"./button":63,"./component":65}],65:[function(_dereq_,module,exports){
/**
* @file component.js
*
* Player Component - Base class for all UI objects
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* Base UI Component class
* Components are embeddable UI objects that are represented by both a
* javascript object and an element in the DOM. They can be children of other
* components, and can have many children themselves.
* ```js
* // adding a button to the player
* var button = player.addChild('button');
* button.el(); // -> button element
* ```
* ```html
* <div class="video-js">
* <div class="vjs-button">Button</div>
* </div>
* ```
* Components are also event targets.
* ```js
* button.on('click', function(){
* console.log('Button Clicked!');
* });
* button.trigger('customevent');
* ```
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @class Component
*/
var Component = (function () {
function Component(player, options, ready) {
_classCallCheck(this, Component);
// The component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this; // eslint-disable-line
} else {
this.player_ = player;
}
// Make a copy of prototype.options_ to protect against overriding defaults
this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_);
// Updated options with supplied options
options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options);
// Get ID from options or options element if one is supplied
this.id_ = options.id || options.el && options.el.id;
// If there was no ID from the options, generate one
if (!this.id_) {
// Don't require the player ID function in the case of mock players
var id = player && player.id && player.id() || 'no_player';
this.id_ = id + '_component_' + Guid.newGUID();
}
this.name_ = options.name || null;
// Create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createEl !== false) {
this.el_ = this.createEl();
}
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
if (options.initChildren !== false) {
this.initChildren();
}
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
}
/**
* Dispose of the component and all child components
*
* @method dispose
*/
Component.prototype.dispose = function dispose() {
this.trigger({ type: 'dispose', bubbles: false });
// Dispose all children.
if (this.children_) {
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
}
// Delete child references
this.children_ = null;
this.childIndex_ = null;
this.childNameIndex_ = null;
// Remove all event listeners.
this.off();
// Remove element from DOM
if (this.el_.parentNode) {
this.el_.parentNode.removeChild(this.el_);
}
Dom.removeElData(this.el_);
this.el_ = null;
};
/**
* Return the component's player
*
* @return {Player}
* @method player
*/
Component.prototype.player = function player() {
return this.player_;
};
/**
* Deep merge of options objects
* Whenever a property is an object on both options objects
* the two properties will be merged using mergeOptions.
*
* ```js
* Parent.prototype.options_ = {
* optionSet: {
* 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' },
* 'childTwo': {},
* 'childThree': {}
* }
* }
* newOptions = {
* optionSet: {
* 'childOne': { 'foo': 'baz', 'abc': '123' }
* 'childTwo': null,
* 'childFour': {}
* }
* }
*
* this.options(newOptions);
* ```
* RESULT
* ```js
* {
* optionSet: {
* 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' },
* 'childTwo': null, // Disabled. Won't be initialized.
* 'childThree': {},
* 'childFour': {}
* }
* }
* ```
*
* @param {Object} obj Object of new option values
* @return {Object} A NEW object of this.options_ and obj merged
* @method options
*/
Component.prototype.options = function options(obj) {
_utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0');
if (!obj) {
return this.options_;
}
this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj);
return this.options_;
};
/**
* Get the component's DOM element
* ```js
* var domEl = myComponent.el();
* ```
*
* @return {Element}
* @method el
*/
Component.prototype.el = function el() {
return this.el_;
};
/**
* Create the component's DOM element
*
* @param {String=} tagName Element's node type. e.g. 'div'
* @param {Object=} properties An object of properties that should be set
* @param {Object=} attributes An object of attributes that should be set
* @return {Element}
* @method createEl
*/
Component.prototype.createEl = function createEl(tagName, properties, attributes) {
return Dom.createEl(tagName, properties, attributes);
};
Component.prototype.localize = function localize(string) {
var code = this.player_.language && this.player_.language();
var languages = this.player_.languages && this.player_.languages();
if (!code || !languages) {
return string;
}
var language = languages[code];
if (language && language[string]) {
return language[string];
}
var primaryCode = code.split('-')[0];
var primaryLang = languages[primaryCode];
if (primaryLang && primaryLang[string]) {
return primaryLang[string];
}
return string;
};
/**
* Return the component's DOM element where children are inserted.
* Will either be the same as el() or a new element defined in createEl().
*
* @return {Element}
* @method contentEl
*/
Component.prototype.contentEl = function contentEl() {
return this.contentEl_ || this.el_;
};
/**
* Get the component's ID
* ```js
* var id = myComponent.id();
* ```
*
* @return {String}
* @method id
*/
Component.prototype.id = function id() {
return this.id_;
};
/**
* Get the component's name. The name is often used to reference the component.
* ```js
* var name = myComponent.name();
* ```
*
* @return {String}
* @method name
*/
Component.prototype.name = function name() {
return this.name_;
};
/**
* Get an array of all child components
* ```js
* var kids = myComponent.children();
* ```
*
* @return {Array} The children
* @method children
*/
Component.prototype.children = function children() {
return this.children_;
};
/**
* Returns a child component with the provided ID
*
* @return {Component}
* @method getChildById
*/
Component.prototype.getChildById = function getChildById(id) {
return this.childIndex_[id];
};
/**
* Returns a child component with the provided name
*
* @return {Component}
* @method getChild
*/
Component.prototype.getChild = function getChild(name) {
return this.childNameIndex_[name];
};
/**
* Adds a child component inside this component
* ```js
* myComponent.el();
* // -> <div class='my-component'></div>
* myComponent.children();
* // [empty array]
*
* var myButton = myComponent.addChild('MyButton');
* // -> <div class='my-component'><div class="my-button">myButton<div></div>
* // -> myButton === myComponent.children()[0];
* ```
* Pass in options for child constructors and options for children of the child
* ```js
* var myButton = myComponent.addChild('MyButton', {
* text: 'Press Me',
* buttonChildExample: {
* buttonChildOption: true
* }
* });
* ```
*
* @param {String|Component} child The class name or instance of a child to add
* @param {Object=} options Options, including options to be passed to children of the child.
* @return {Component} The child component (created by this process if a string was used)
* @method addChild
*/
Component.prototype.addChild = function addChild(child) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var component = undefined;
var componentName = undefined;
// If child is a string, create nt with options
if (typeof child === 'string') {
componentName = child;
// Options can also be specified as a boolean, so convert to an empty object if false.
if (!options) {
options = {};
}
// Same as above, but true is deprecated so show a warning.
if (options === true) {
_utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.');
options = {};
}
// If no componentClass in options, assume componentClass is the name lowercased
// (e.g. playButton)
var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](componentName);
// Set name through options
options.name = componentName;
// Create a new object & element for this controls set
// If there's no .player_, this is a player
var ComponentClass = Component.getComponent(componentClassName);
if (!ComponentClass) {
throw new Error('Component ' + componentClassName + ' does not exist');
}
// data stored directly on the videojs object may be
// misidentified as a component to retain
// backwards-compatibility with 4.x. check to make sure the
// component class can be instantiated.
if (typeof ComponentClass !== 'function') {
return null;
}
component = new ComponentClass(this.player_ || this, options);
// child is a component instance
} else {
component = child;
}
this.children_.push(component);
if (typeof component.id === 'function') {
this.childIndex_[component.id()] = component;
}
// If a name wasn't used to create the component, check if we can use the
// name function of the component
componentName = componentName || component.name && component.name();
if (componentName) {
this.childNameIndex_[componentName] = component;
}
// Add the UI object's element to the container div (box)
// Having an element is not required
if (typeof component.el === 'function' && component.el()) {
this.contentEl().appendChild(component.el());
}
// Return so it can stored on parent object if desired.
return component;
};
/**
* Remove a child component from this component's list of children, and the
* child component's element from this component's element
*
* @param {Component} component Component to remove
* @method removeChild
*/
Component.prototype.removeChild = function removeChild(component) {
if (typeof component === 'string') {
component = this.getChild(component);
}
if (!component || !this.children_) {
return;
}
var childFound = false;
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childFound = true;
this.children_.splice(i, 1);
break;
}
}
if (!childFound) {
return;
}
this.childIndex_[component.id()] = null;
this.childNameIndex_[component.name()] = null;
var compEl = component.el();
if (compEl && compEl.parentNode === this.contentEl()) {
this.contentEl().removeChild(component.el());
}
};
/**
* Add and initialize default child components from options
* ```js
* // when an instance of MyComponent is created, all children in options
* // will be added to the instance by their name strings and options
* MyComponent.prototype.options_ = {
* children: [
* 'myChildComponent'
* ],
* myChildComponent: {
* myChildOption: true
* }
* };
*
* // Or when creating the component
* var myComp = new MyComponent(player, {
* children: [
* 'myChildComponent'
* ],
* myChildComponent: {
* myChildOption: true
* }
* });
* ```
* The children option can also be an array of
* child options objects (that also include a 'name' key).
* This can be used if you have two child components of the
* same type that need different options.
* ```js
* var myComp = new MyComponent(player, {
* children: [
* 'button',
* {
* name: 'button',
* someOtherOption: true
* },
* {
* name: 'button',
* someOtherOption: false
* }
* ]
* });
* ```
*
* @method initChildren
*/
Component.prototype.initChildren = function initChildren() {
var _this = this;
var children = this.options_.children;
if (children) {
(function () {
// `this` is `parent`
var parentOptions = _this.options_;
var handleAdd = function handleAdd(child) {
var name = child.name;
var opts = child.opts;
// Allow options for children to be set at the parent options
// e.g. videojs(id, { controlBar: false });
// instead of videojs(id, { children: { controlBar: false });
if (parentOptions[name] !== undefined) {
opts = parentOptions[name];
}
// Allow for disabling default components
// e.g. options['children']['posterImage'] = false
if (opts === false) {
return;
}
// Allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
}
// We also want to pass the original player options to each component as well so they don't need to
// reach back into the player for options later.
opts.playerOptions = _this.options_.playerOptions;
// Create and add the child component.
// Add a direct reference to the child by name on the parent instance.
// If two of the same component are used, different names should be supplied
// for each
var newChild = _this.addChild(name, opts);
if (newChild) {
_this[name] = newChild;
}
};
// Allow for an array of children details to passed in the options
var workingChildren = undefined;
var Tech = Component.getComponent('Tech');
if (Array.isArray(children)) {
workingChildren = children;
} else {
workingChildren = Object.keys(children);
}
workingChildren
// children that are in this.options_ but also in workingChildren would
// give us extra children we do not want. So, we want to filter them out.
.concat(Object.keys(_this.options_).filter(function (child) {
return !workingChildren.some(function (wchild) {
if (typeof wchild === 'string') {
return child === wchild;
} else {
return child === wchild.name;
}
});
})).map(function (child) {
var name = undefined,
opts = undefined;
if (typeof child === 'string') {
name = child;
opts = children[name] || _this.options_[name] || {};
} else {
name = child.name;
opts = child;
}
return { name: name, opts: opts };
}).filter(function (child) {
// we have to make sure that child.name isn't in the techOrder since
// techs are registerd as Components but can't aren't compatible
// See https://github.com/videojs/video.js/issues/2772
var c = Component.getComponent(child.opts.componentClass || _utilsToTitleCaseJs2['default'](child.name));
return c && !Tech.isTech(c);
}).forEach(handleAdd);
})();
}
};
/**
* Allows sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Component.prototype.buildCSSClass = function buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
};
/**
* Add an event listener to this component's element
* ```js
* var myFunc = function(){
* var myComponent = this;
* // Do something when the event is fired
* };
*
* myComponent.on('eventType', myFunc);
* ```
* The context of myFunc will be myComponent unless previously bound.
* Alternatively, you can add a listener to another element or component.
* ```js
* myComponent.on(otherElement, 'eventName', myFunc);
* myComponent.on(otherComponent, 'eventName', myFunc);
* ```
* The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)`
* and `otherComponent.on('eventName', myFunc)` is that this way the listeners
* will be automatically cleaned up when either component is disposed.
* It will also bind myComponent as the context of myFunc.
* **NOTE**: When using this on elements in the page other than window
* and document (both permanent), if you remove the element from the DOM
* you need to call `myComponent.trigger(el, 'dispose')` on it to clean up
* references to it and allow the browser to garbage collect it.
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The event handler or event type
* @param {Function} third The event handler
* @return {Component}
* @method on
*/
Component.prototype.on = function on(first, second, third) {
var _this2 = this;
if (typeof first === 'string' || Array.isArray(first)) {
Events.on(this.el_, first, Fn.bind(this, second));
// Targeting another component or element
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this2, third);
// When this component is disposed, remove the listener from the other component
var removeOnDispose = function removeOnDispose() {
return _this2.off(target, type, fn);
};
// Use the same function ID so we can remove it later it using the ID
// of the original listener
removeOnDispose.guid = fn.guid;
_this2.on('dispose', removeOnDispose);
// If the other component is disposed first we need to clean the reference
// to the other component in this component's removeOnDispose listener
// Otherwise we create a memory leak.
var cleanRemover = function cleanRemover() {
return _this2.off('dispose', removeOnDispose);
};
// Add the same function ID so we can easily remove it later
cleanRemover.guid = fn.guid;
// Check if this is a DOM node
if (first.nodeName) {
// Add the listener to the other element
Events.on(target, type, fn);
Events.on(target, 'dispose', cleanRemover);
// Should be a component
// Not using `instanceof Component` because it makes mock players difficult
} else if (typeof first.on === 'function') {
// Add the listener to the other component
target.on(type, fn);
target.on('dispose', cleanRemover);
}
})();
}
return this;
};
/**
* Remove an event listener from this component's element
* ```js
* myComponent.off('eventType', myFunc);
* ```
* If myFunc is excluded, ALL listeners for the event type will be removed.
* If eventType is excluded, ALL listeners will be removed from the component.
* Alternatively you can use `off` to remove listeners that were added to other
* elements or components using `myComponent.on(otherComponent...`.
* In this case both the event type and listener function are REQUIRED.
* ```js
* myComponent.off(otherElement, 'eventType', myFunc);
* myComponent.off(otherComponent, 'eventType', myFunc);
* ```
*
* @param {String=|Component} first The event type or other component
* @param {Function=|String} second The listener function or event type
* @param {Function=} third The listener for other component
* @return {Component}
* @method off
*/
Component.prototype.off = function off(first, second, third) {
if (!first || typeof first === 'string' || Array.isArray(first)) {
Events.off(this.el_, first, second);
} else {
var target = first;
var type = second;
// Ensure there's at least a guid, even if the function hasn't been used
var fn = Fn.bind(this, third);
// Remove the dispose listener on this component,
// which was given the same guid as the event listener
this.off('dispose', fn);
if (first.nodeName) {
// Remove the listener
Events.off(target, type, fn);
// Remove the listener for cleaning the dispose listener
Events.off(target, 'dispose', fn);
} else {
target.off(type, fn);
target.off('dispose', fn);
}
}
return this;
};
/**
* Add an event listener to be triggered only once and then removed
* ```js
* myComponent.one('eventName', myFunc);
* ```
* Alternatively you can add a listener to another element or component
* that will be triggered only once.
* ```js
* myComponent.one(otherElement, 'eventName', myFunc);
* myComponent.one(otherComponent, 'eventName', myFunc);
* ```
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The listener function or event type
* @param {Function=} third The listener function for other component
* @return {Component}
* @method one
*/
Component.prototype.one = function one(first, second, third) {
var _this3 = this,
_arguments = arguments;
if (typeof first === 'string' || Array.isArray(first)) {
Events.one(this.el_, first, Fn.bind(this, second));
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this3, third);
var newFunc = function newFunc() {
_this3.off(target, type, newFunc);
fn.apply(null, _arguments);
};
// Keep the same function ID so we can remove it later
newFunc.guid = fn.guid;
_this3.on(target, type, newFunc);
})();
}
return this;
};
/**
* Trigger an event on an element
* ```js
* myComponent.trigger('eventName');
* myComponent.trigger({'type':'eventName'});
* myComponent.trigger('eventName', {data: 'some data'});
* myComponent.trigger({'type':'eventName'}, {data: 'some data'});
* ```
*
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @param {Object} [hash] data hash to pass along with the event
* @return {Component} self
* @method trigger
*/
Component.prototype.trigger = function trigger(event, hash) {
Events.trigger(this.el_, event, hash);
return this;
};
/**
* Bind a listener to the component's ready state.
* Different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @param {Function} fn Ready listener
* @param {Boolean} sync Exec the listener synchronously if component is ready
* @return {Component}
* @method ready
*/
Component.prototype.ready = function ready(fn) {
var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (fn) {
if (this.isReady_) {
if (sync) {
fn.call(this);
} else {
// Call the function asynchronously by default for consistency
this.setTimeout(fn, 1);
}
} else {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
}
}
return this;
};
/**
* Trigger the ready listeners
*
* @return {Component}
* @method triggerReady
*/
Component.prototype.triggerReady = function triggerReady() {
this.isReady_ = true;
// Ensure ready is triggerd asynchronously
this.setTimeout(function () {
var readyQueue = this.readyQueue_;
// Reset Ready Queue
this.readyQueue_ = [];
if (readyQueue && readyQueue.length > 0) {
readyQueue.forEach(function (fn) {
fn.call(this);
}, this);
}
// Allow for using event listeners also
this.trigger('ready');
}, 1);
};
/**
* Finds a single DOM element matching `selector` within the component's
* `contentEl` or another custom context.
*
* @method $
* @param {String} selector
* A valid CSS selector, which will be passed to `querySelector`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {Element|null}
*/
Component.prototype.$ = function $(selector, context) {
return Dom.$(selector, context || this.contentEl());
};
/**
* Finds a all DOM elements matching `selector` within the component's
* `contentEl` or another custom context.
*
* @method $$
* @param {String} selector
* A valid CSS selector, which will be passed to `querySelectorAll`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {NodeList}
*/
Component.prototype.$$ = function $$(selector, context) {
return Dom.$$(selector, context || this.contentEl());
};
/**
* Check if a component's element has a CSS class name
*
* @param {String} classToCheck Classname to check
* @return {Component}
* @method hasClass
*/
Component.prototype.hasClass = function hasClass(classToCheck) {
return Dom.hasElClass(this.el_, classToCheck);
};
/**
* Add a CSS class name to the component's element
*
* @param {String} classToAdd Classname to add
* @return {Component}
* @method addClass
*/
Component.prototype.addClass = function addClass(classToAdd) {
Dom.addElClass(this.el_, classToAdd);
return this;
};
/**
* Remove a CSS class name from the component's element
*
* @param {String} classToRemove Classname to remove
* @return {Component}
* @method removeClass
*/
Component.prototype.removeClass = function removeClass(classToRemove) {
Dom.removeElClass(this.el_, classToRemove);
return this;
};
/**
* Add or remove a CSS class name from the component's element
*
* @param {String} classToToggle
* @param {Boolean|Function} [predicate]
* Can be a function that returns a Boolean. If `true`, the class
* will be added; if `false`, the class will be removed. If not
* given, the class will be added if not present and vice versa.
*
* @return {Component}
* @method toggleClass
*/
Component.prototype.toggleClass = function toggleClass(classToToggle, predicate) {
Dom.toggleElClass(this.el_, classToToggle, predicate);
return this;
};
/**
* Show the component element if hidden
*
* @return {Component}
* @method show
*/
Component.prototype.show = function show() {
this.removeClass('vjs-hidden');
return this;
};
/**
* Hide the component element if currently showing
*
* @return {Component}
* @method hide
*/
Component.prototype.hide = function hide() {
this.addClass('vjs-hidden');
return this;
};
/**
* Lock an item in its visible state
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method lockShowing
*/
Component.prototype.lockShowing = function lockShowing() {
this.addClass('vjs-lock-showing');
return this;
};
/**
* Unlock an item to be hidden
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method unlockShowing
*/
Component.prototype.unlockShowing = function unlockShowing() {
this.removeClass('vjs-lock-showing');
return this;
};
/**
* Set or get the width of the component (CSS values)
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num Optional width number
* @param {Boolean} skipListeners Skip the 'resize' event trigger
* @return {Component} This component, when setting the width
* @return {Number|String} The width, when getting
* @method width
*/
Component.prototype.width = function width(num, skipListeners) {
return this.dimension('width', num, skipListeners);
};
/**
* Get or set the height of the component (CSS values)
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num New component height
* @param {Boolean=} skipListeners Skip the resize event trigger
* @return {Component} This component, when setting the height
* @return {Number|String} The height, when getting
* @method height
*/
Component.prototype.height = function height(num, skipListeners) {
return this.dimension('height', num, skipListeners);
};
/**
* Set both width and height at the same time
*
* @param {Number|String} width Width of player
* @param {Number|String} height Height of player
* @return {Component} The component
* @method dimensions
*/
Component.prototype.dimensions = function dimensions(width, height) {
// Skip resize listeners on width for optimization
return this.width(width, true).height(height);
};
/**
* Get or set width or height
* This is the shared code for the width() and height() methods.
* All for an integer, integer + 'px' or integer + '%';
* Known issue: Hidden elements officially have a width of 0. We're defaulting
* to the style.width value and falling back to computedStyle which has the
* hidden element issue. Info, but probably not an efficient fix:
* http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/
*
* @param {String} widthOrHeight 'width' or 'height'
* @param {Number|String=} num New dimension
* @param {Boolean=} skipListeners Skip resize event trigger
* @return {Component} The component if a dimension was set
* @return {Number|String} The dimension if nothing was set
* @private
* @method dimension
*/
Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) {
if (num !== undefined) {
// Set to zero if null or literally NaN (NaN !== NaN)
if (num === null || num !== num) {
num = 0;
}
// Check if using css width/height (% or px) and adjust
if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
this.el_.style[widthOrHeight] = num;
} else if (num === 'auto') {
this.el_.style[widthOrHeight] = '';
} else {
this.el_.style[widthOrHeight] = num + 'px';
}
// skipListeners allows us to avoid triggering the resize event when setting both width and height
if (!skipListeners) {
this.trigger('resize');
}
// Return component
return this;
}
// Not setting a value, so getting it
// Make sure element exists
if (!this.el_) {
return 0;
}
// Get dimension value from style
var val = this.el_.style[widthOrHeight];
var pxIndex = val.indexOf('px');
if (pxIndex !== -1) {
// Return the pixel value with no 'px'
return parseInt(val.slice(0, pxIndex), 10);
}
// No px so using % or no style was set, so falling back to offsetWidth/height
// If component has display:none, offset will return 0
// TODO: handle display:none and no dimension style using px
return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10);
};
/**
* Emit 'tap' events when touch events are supported
* This is used to support toggling the controls through a tap on the video.
* We're requiring them to be enabled because otherwise every component would
* have this extra overhead unnecessarily, on mobile devices where extra
* overhead is especially bad.
*
* @private
* @method emitTapEvents
*/
Component.prototype.emitTapEvents = function emitTapEvents() {
// Track the start time so we can determine how long the touch lasted
var touchStart = 0;
var firstTouch = null;
// Maximum movement allowed during a touch event to still be considered a tap
// Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number.
var tapMovementThreshold = 10;
// The maximum length a touch can be while still being considered a tap
var touchTimeThreshold = 200;
var couldBeTap = undefined;
this.on('touchstart', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
// Copy the touches object to prevent modifying the original
firstTouch = _objectAssign2['default']({}, event.touches[0]);
// Record start time so we can detect a tap vs. "touch and hold"
touchStart = new Date().getTime();
// Reset couldBeTap tracking
couldBeTap = true;
}
});
this.on('touchmove', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length > 1) {
couldBeTap = false;
} else if (firstTouch) {
// Some devices will throw touchmoves for all but the slightest of taps.
// So, if we moved only a small distance, this could still be a tap
var xdiff = event.touches[0].pageX - firstTouch.pageX;
var ydiff = event.touches[0].pageY - firstTouch.pageY;
var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchDistance > tapMovementThreshold) {
couldBeTap = false;
}
}
});
var noTap = function noTap() {
couldBeTap = false;
};
// TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
this.on('touchleave', noTap);
this.on('touchcancel', noTap);
// When the touch ends, measure how long it took and trigger the appropriate
// event
this.on('touchend', function (event) {
firstTouch = null;
// Proceed only if the touchmove/leave/cancel event didn't happen
if (couldBeTap === true) {
// Measure how long the touch lasted
var touchTime = new Date().getTime() - touchStart;
// Make sure the touch was less than the threshold to be considered a tap
if (touchTime < touchTimeThreshold) {
// Don't let browser turn this into a click
event.preventDefault();
this.trigger('tap');
// It may be good to copy the touchend event object and change the
// type to tap, if the other event properties aren't exact after
// Events.fixEvent runs (e.g. event.target)
}
}
});
};
/**
* Report user touch activity when touch events occur
* User activity is used to determine when controls should show/hide. It's
* relatively simple when it comes to mouse events, because any mouse event
* should show the controls. So we capture mouse events that bubble up to the
* player and report activity when that happens.
* With touch events it isn't as easy. We can't rely on touch events at the
* player level, because a tap (touchstart + touchend) on the video itself on
* mobile devices is meant to turn controls off (and on). User activity is
* checked asynchronously, so what could happen is a tap event on the video
* turns the controls off, then the touchend event bubbles up to the player,
* which if it reported user activity, would turn the controls right back on.
* (We also don't want to completely block touch events from bubbling up)
* Also a touchmove, touch+hold, and anything other than a tap is not supposed
* to turn the controls back on on a mobile device.
* Here we're setting the default component behavior to report user activity
* whenever touch events happen, and this can be turned off by components that
* want touch events to act differently.
*
* @method enableTouchActivity
*/
Component.prototype.enableTouchActivity = function enableTouchActivity() {
// Don't continue if the root player doesn't support reporting user activity
if (!this.player() || !this.player().reportUserActivity) {
return;
}
// listener for reporting that the user is active
var report = Fn.bind(this.player(), this.player().reportUserActivity);
var touchHolding = undefined;
this.on('touchstart', function () {
report();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(touchHolding);
// report at the same interval as activityCheck
touchHolding = this.setInterval(report, 250);
});
var touchEnd = function touchEnd(event) {
report();
// stop the interval that maintains activity if the touch is holding
this.clearInterval(touchHolding);
};
this.on('touchmove', report);
this.on('touchend', touchEnd);
this.on('touchcancel', touchEnd);
};
/**
* Creates timeout and sets up disposal automatically.
*
* @param {Function} fn The function to run after the timeout.
* @param {Number} timeout Number of ms to delay before executing specified function.
* @return {Number} Returns the timeout ID
* @method setTimeout
*/
Component.prototype.setTimeout = function setTimeout(fn, timeout) {
fn = Fn.bind(this, fn);
// window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't.
var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout);
var disposeFn = function disposeFn() {
this.clearTimeout(timeoutId);
};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.on('dispose', disposeFn);
return timeoutId;
};
/**
* Clears a timeout and removes the associated dispose listener
*
* @param {Number} timeoutId The id of the timeout to clear
* @return {Number} Returns the timeout ID
* @method clearTimeout
*/
Component.prototype.clearTimeout = function clearTimeout(timeoutId) {
_globalWindow2['default'].clearTimeout(timeoutId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.off('dispose', disposeFn);
return timeoutId;
};
/**
* Creates an interval and sets up disposal automatically.
*
* @param {Function} fn The function to run every N seconds.
* @param {Number} interval Number of ms to delay before executing specified function.
* @return {Number} Returns the interval ID
* @method setInterval
*/
Component.prototype.setInterval = function setInterval(fn, interval) {
fn = Fn.bind(this, fn);
var intervalId = _globalWindow2['default'].setInterval(fn, interval);
var disposeFn = function disposeFn() {
this.clearInterval(intervalId);
};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.on('dispose', disposeFn);
return intervalId;
};
/**
* Clears an interval and removes the associated dispose listener
*
* @param {Number} intervalId The id of the interval to clear
* @return {Number} Returns the interval ID
* @method clearInterval
*/
Component.prototype.clearInterval = function clearInterval(intervalId) {
_globalWindow2['default'].clearInterval(intervalId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.off('dispose', disposeFn);
return intervalId;
};
/**
* Registers a component
*
* @param {String} name Name of the component to register
* @param {Object} comp The component to register
* @static
* @method registerComponent
*/
Component.registerComponent = function registerComponent(name, comp) {
if (!Component.components_) {
Component.components_ = {};
}
Component.components_[name] = comp;
return comp;
};
/**
* Gets a component by name
*
* @param {String} name Name of the component to get
* @return {Component}
* @static
* @method getComponent
*/
Component.getComponent = function getComponent(name) {
if (Component.components_ && Component.components_[name]) {
return Component.components_[name];
}
if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) {
_utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)');
return _globalWindow2['default'].videojs[name];
}
};
/**
* Sets up the constructor using the supplied init method
* or uses the init of the parent object
*
* @param {Object} props An object of properties
* @static
* @deprecated
* @method extend
*/
Component.extend = function extend(props) {
props = props || {};
_utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extend(Component, {}) instead');
// Set up the constructor using the supplied init method
// or using the init of the parent object
// Make sure to check the unobfuscated version for external libs
var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {};
// In Resig's simple class inheritance (previously used) the constructor
// is a function that calls `this.init.apply(arguments)`
// However that would prevent us from using `ParentObject.call(this);`
// in a Child constructor because the `this` in `this.init`
// would still refer to the Child and cause an infinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, arguments);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
var subObj = function subObj() {
init.apply(this, arguments);
};
// Inherit from this object's prototype
subObj.prototype = Object.create(this.prototype);
// Reset the constructor property for subObj otherwise
// instances of subObj would have the constructor of the parent Object
subObj.prototype.constructor = subObj;
// Make the class extendable
subObj.extend = Component.extend;
// Extend subObj's prototype with functions and other properties from props
for (var _name in props) {
if (props.hasOwnProperty(_name)) {
subObj.prototype[_name] = props[_name];
}
}
return subObj;
};
return Component;
})();
Component.registerComponent('Component', Component);
exports['default'] = Component;
module.exports = exports['default'];
},{"./utils/dom.js":128,"./utils/events.js":129,"./utils/fn.js":130,"./utils/guid.js":132,"./utils/log.js":133,"./utils/merge-options.js":134,"./utils/to-title-case.js":137,"global/window":2,"object.assign":45}],66:[function(_dereq_,module,exports){
/**
* @file control-bar.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _playToggleJs = _dereq_('./play-toggle.js');
var _playToggleJs2 = _interopRequireDefault(_playToggleJs);
var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js');
var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs);
var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js');
var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs);
var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js');
var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs);
var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js');
var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs);
var _liveDisplayJs = _dereq_('./live-display.js');
var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs);
var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js');
var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs);
var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js');
var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs);
var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js');
var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs);
var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js');
var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js');
var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs);
var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js');
var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs);
var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js');
var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs);
var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js');
var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs);
var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js');
var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs);
/**
* Container of main controls
*
* @extends Component
* @class ControlBar
*/
var ControlBar = (function (_Component) {
_inherits(ControlBar, _Component);
function ControlBar() {
_classCallCheck(this, ControlBar);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ControlBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-control-bar'
});
};
return ControlBar;
})(_componentJs2['default']);
ControlBar.prototype.options_ = {
loadEvent: 'play',
children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle']
};
_componentJs2['default'].registerComponent('ControlBar', ControlBar);
exports['default'] = ControlBar;
module.exports = exports['default'];
},{"../component.js":65,"./fullscreen-toggle.js":67,"./live-display.js":68,"./mute-toggle.js":69,"./play-toggle.js":70,"./playback-rate-menu/playback-rate-menu-button.js":71,"./progress-control/progress-control.js":76,"./spacer-controls/custom-control-spacer.js":78,"./text-track-controls/captions-button.js":81,"./text-track-controls/chapters-button.js":82,"./text-track-controls/subtitles-button.js":85,"./time-controls/current-time-display.js":88,"./time-controls/duration-display.js":89,"./time-controls/remaining-time-display.js":90,"./time-controls/time-divider.js":91,"./volume-control/volume-control.js":93,"./volume-menu-button.js":95}],67:[function(_dereq_,module,exports){
/**
* @file fullscreen-toggle.js
*/
'use strict';
exports.__esModule = true;
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 _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Toggle fullscreen video
*
* @extends Button
* @class FullscreenToggle
*/
var FullscreenToggle = (function (_Button) {
_inherits(FullscreenToggle, _Button);
function FullscreenToggle() {
_classCallCheck(this, FullscreenToggle);
_Button.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handles click for full screen
*
* @method handleClick
*/
FullscreenToggle.prototype.handleClick = function handleClick() {
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
this.controlText('Non-Fullscreen');
} else {
this.player_.exitFullscreen();
this.controlText('Fullscreen');
}
};
return FullscreenToggle;
})(_buttonJs2['default']);
FullscreenToggle.prototype.controlText_ = 'Fullscreen';
_componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle);
exports['default'] = FullscreenToggle;
module.exports = exports['default'];
},{"../button.js":63,"../component.js":65}],68:[function(_dereq_,module,exports){
/**
* @file live-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Displays the live indicator
* TODO - Future make it click to snap to live
*
* @extends Component
* @class LiveDisplay
*/
var LiveDisplay = (function (_Component) {
_inherits(LiveDisplay, _Component);
function LiveDisplay(player, options) {
_classCallCheck(this, LiveDisplay);
_Component.call(this, player, options);
this.updateShowing();
this.on(this.player(), 'durationchange', this.updateShowing);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LiveDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-live-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-live-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE')
}, {
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
LiveDisplay.prototype.updateShowing = function updateShowing() {
if (this.player().duration() === Infinity) {
this.show();
} else {
this.hide();
}
};
return LiveDisplay;
})(_component2['default']);
_component2['default'].registerComponent('LiveDisplay', LiveDisplay);
exports['default'] = LiveDisplay;
module.exports = exports['default'];
},{"../component":65,"../utils/dom.js":128}],69:[function(_dereq_,module,exports){
/**
* @file mute-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _button = _dereq_('../button');
var _button2 = _interopRequireDefault(_button);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* A button component for muting the audio
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MuteToggle
*/
var MuteToggle = (function (_Button) {
_inherits(MuteToggle, _Button);
function MuteToggle(player, options) {
_classCallCheck(this, MuteToggle);
_Button.call(this, player, options);
this.on(player, 'volumechange', this.update);
// hide mute toggle if the current tech doesn't support volume control
if (player.tech_ && player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
}
this.on(player, 'loadstart', function () {
this.update(); // We need to update the button to account for a default muted state.
if (player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MuteToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click on mute
*
* @method handleClick
*/
MuteToggle.prototype.handleClick = function handleClick() {
this.player_.muted(this.player_.muted() ? false : true);
};
/**
* Update volume
*
* @method update
*/
MuteToggle.prototype.update = function update() {
var vol = this.player_.volume(),
level = 3;
if (vol === 0 || this.player_.muted()) {
level = 0;
} else if (vol < 0.33) {
level = 1;
} else if (vol < 0.67) {
level = 2;
}
// Don't rewrite the button text if the actual text doesn't change.
// This causes unnecessary and confusing information for screen reader users.
// This check is needed because this function gets called every time the volume level is changed.
var toMute = this.player_.muted() ? 'Unmute' : 'Mute';
var localizedMute = this.localize(toMute);
if (this.controlText() !== localizedMute) {
this.controlText(localizedMute);
}
/* TODO improve muted icon classes */
for (var i = 0; i < 4; i++) {
Dom.removeElClass(this.el_, 'vjs-vol-' + i);
}
Dom.addElClass(this.el_, 'vjs-vol-' + level);
};
return MuteToggle;
})(_button2['default']);
MuteToggle.prototype.controlText_ = 'Mute';
_component2['default'].registerComponent('MuteToggle', MuteToggle);
exports['default'] = MuteToggle;
module.exports = exports['default'];
},{"../button":63,"../component":65,"../utils/dom.js":128}],70:[function(_dereq_,module,exports){
/**
* @file play-toggle.js
*/
'use strict';
exports.__esModule = true;
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 _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Button to toggle between play and pause
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PlayToggle
*/
var PlayToggle = (function (_Button) {
_inherits(PlayToggle, _Button);
function PlayToggle(player, options) {
_classCallCheck(this, PlayToggle);
_Button.call(this, player, options);
this.on(player, 'play', this.handlePlay);
this.on(player, 'pause', this.handlePause);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlayToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click to toggle between play and pause
*
* @method handleClick
*/
PlayToggle.prototype.handleClick = function handleClick() {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
/**
* Add the vjs-playing class to the element so it can change appearance
*
* @method handlePlay
*/
PlayToggle.prototype.handlePlay = function handlePlay() {
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
this.controlText('Pause'); // change the button text to "Pause"
};
/**
* Add the vjs-paused class to the element so it can change appearance
*
* @method handlePause
*/
PlayToggle.prototype.handlePause = function handlePause() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.controlText('Play'); // change the button text to "Play"
};
return PlayToggle;
})(_buttonJs2['default']);
PlayToggle.prototype.controlText_ = 'Play';
_componentJs2['default'].registerComponent('PlayToggle', PlayToggle);
exports['default'] = PlayToggle;
module.exports = exports['default'];
},{"../button.js":63,"../component.js":65}],71:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js');
var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* The component for controlling the playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class PlaybackRateMenuButton
*/
var PlaybackRateMenuButton = (function (_MenuButton) {
_inherits(PlaybackRateMenuButton, _MenuButton);
function PlaybackRateMenuButton(player, options) {
_classCallCheck(this, PlaybackRateMenuButton);
_MenuButton.call(this, player, options);
this.updateVisibility();
this.updateLabel();
this.on(player, 'loadstart', this.updateVisibility);
this.on(player, 'ratechange', this.updateLabel);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlaybackRateMenuButton.prototype.createEl = function createEl() {
var el = _MenuButton.prototype.createEl.call(this);
this.labelEl_ = Dom.createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: 1.0
});
el.appendChild(this.labelEl_);
return el;
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this);
};
/**
* Create the playback rate menu
*
* @return {Menu} Menu object populated with items
* @method createMenu
*/
PlaybackRateMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player());
var rates = this.playbackRates();
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' }));
}
}
return menu;
};
/**
* Updates ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
};
/**
* Handle menu item click
*
* @method handleClick
*/
PlaybackRateMenuButton.prototype.handleClick = function handleClick() {
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.playbackRates();
// this will select first one if the last one currently selected
var newRate = rates[0];
for (var i = 0; i < rates.length; i++) {
if (rates[i] > currentRate) {
newRate = rates[i];
break;
}
}
this.player().playbackRate(newRate);
};
/**
* Get possible playback rates
*
* @return {Array} Possible playback rates
* @method playbackRates
*/
PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() {
return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates'];
};
/**
* Get supported playback rates
*
* @return {Array} Supported playback rates
* @method playbackRateSupported
*/
PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() {
return this.player().tech_ && this.player().tech_['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0;
};
/**
* Hide playback rate controls when they're no playback rate options to select
*
* @method updateVisibility
*/
PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() {
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
};
/**
* Update button label when rate changed
*
* @method updateLabel
*/
PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() {
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
};
return PlaybackRateMenuButton;
})(_menuMenuButtonJs2['default']);
PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
_componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
exports['default'] = PlaybackRateMenuButton;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu-button.js":102,"../../menu/menu.js":104,"../../utils/dom.js":128,"./playback-rate-menu-item.js":72}],72:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-item.js
*/
'use strict';
exports.__esModule = true;
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 _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The specific menu item type for selecting a playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class PlaybackRateMenuItem
*/
var PlaybackRateMenuItem = (function (_MenuItem) {
_inherits(PlaybackRateMenuItem, _MenuItem);
function PlaybackRateMenuItem(player, options) {
_classCallCheck(this, PlaybackRateMenuItem);
var label = options['rate'];
var rate = parseFloat(label, 10);
// Modify options for parent MenuItem class's init.
options['label'] = label;
options['selected'] = rate === 1;
_MenuItem.call(this, player, options);
this.label = label;
this.rate = rate;
this.on(player, 'ratechange', this.update);
}
/**
* Handle click on menu item
*
* @method handleClick
*/
PlaybackRateMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player().playbackRate(this.rate);
};
/**
* Update playback rate with selected rate
*
* @method update
*/
PlaybackRateMenuItem.prototype.update = function update() {
this.selected(this.player().playbackRate() === this.rate);
};
return PlaybackRateMenuItem;
})(_menuMenuItemJs2['default']);
PlaybackRateMenuItem.prototype.contentElType = 'button';
_componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
exports['default'] = PlaybackRateMenuItem;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu-item.js":103}],73:[function(_dereq_,module,exports){
/**
* @file load-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Shows load progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class LoadProgressBar
*/
var LoadProgressBar = (function (_Component) {
_inherits(LoadProgressBar, _Component);
function LoadProgressBar(player, options) {
_classCallCheck(this, LoadProgressBar);
_Component.call(this, player, options);
this.on(player, 'progress', this.update);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LoadProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
};
/**
* Update progress bar
*
* @method update
*/
LoadProgressBar.prototype.update = function update() {
var buffered = this.player_.buffered();
var duration = this.player_.duration();
var bufferedEnd = this.player_.bufferedEnd();
var children = this.el_.children;
// get the percent width of a time compared to the total end
var percentify = function percentify(time, end) {
var percent = time / end || 0; // no NaN
return (percent >= 1 ? 1 : percent) * 100 + '%';
};
// update the width of the progress bar
this.el_.style.width = percentify(bufferedEnd, duration);
// add child elements to represent the individual buffered time ranges
for (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i);
var end = buffered.end(i);
var part = children[i];
if (!part) {
part = this.el_.appendChild(Dom.createEl());
}
// set the percent based on the width of the progress bar (bufferedEnd)
part.style.left = percentify(start, bufferedEnd);
part.style.width = percentify(end - start, bufferedEnd);
}
// remove unused buffered range elements
for (var i = children.length; i > buffered.length; i--) {
this.el_.removeChild(children[i - 1]);
}
};
return LoadProgressBar;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar);
exports['default'] = LoadProgressBar;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/dom.js":128}],74:[function(_dereq_,module,exports){
/**
* @file mouse-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _lodashCompatFunctionThrottle = _dereq_('lodash-compat/function/throttle');
var _lodashCompatFunctionThrottle2 = _interopRequireDefault(_lodashCompatFunctionThrottle);
/**
* The Mouse Time Display component shows the time you will seek to
* when hovering over the progress bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class MouseTimeDisplay
*/
var MouseTimeDisplay = (function (_Component) {
_inherits(MouseTimeDisplay, _Component);
function MouseTimeDisplay(player, options) {
var _this = this;
_classCallCheck(this, MouseTimeDisplay);
_Component.call(this, player, options);
this.update(0, 0);
player.on('ready', function () {
_this.on(player.controlBar.progressControl.el(), 'mousemove', _lodashCompatFunctionThrottle2['default'](Fn.bind(_this, _this.handleMouseMove), 25));
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MouseTimeDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-mouse-display'
});
};
MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) {
var duration = this.player_.duration();
var newTime = this.calculateDistance(event) * duration;
var position = event.pageX - Dom.findElPosition(this.el().parentNode).left;
this.update(newTime, position);
};
MouseTimeDisplay.prototype.update = function update(newTime, position) {
var time = _utilsFormatTimeJs2['default'](newTime, this.player_.duration());
this.el().style.left = position + 'px';
this.el().setAttribute('data-current-time', time);
};
MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) {
return Dom.getPointerPosition(this.el().parentNode, event).x;
};
return MouseTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay);
exports['default'] = MouseTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/dom.js":128,"../../utils/fn.js":130,"../../utils/format-time.js":131,"lodash-compat/function/throttle":7}],75:[function(_dereq_,module,exports){
/**
* @file play-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Shows play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class PlayProgressBar
*/
var PlayProgressBar = (function (_Component) {
_inherits(PlayProgressBar, _Component);
function PlayProgressBar(player, options) {
_classCallCheck(this, PlayProgressBar);
_Component.call(this, player, options);
this.updateDataAttr();
this.on(player, 'timeupdate', this.updateDataAttr);
player.ready(Fn.bind(this, this.updateDataAttr));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlayProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-play-progress vjs-slider-bar',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
};
PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() {
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration()));
};
return PlayProgressBar;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar);
exports['default'] = PlayProgressBar;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/fn.js":130,"../../utils/format-time.js":131}],76:[function(_dereq_,module,exports){
/**
* @file progress-control.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _seekBarJs = _dereq_('./seek-bar.js');
var _seekBarJs2 = _interopRequireDefault(_seekBarJs);
var _mouseTimeDisplayJs = _dereq_('./mouse-time-display.js');
var _mouseTimeDisplayJs2 = _interopRequireDefault(_mouseTimeDisplayJs);
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class ProgressControl
*/
var ProgressControl = (function (_Component) {
_inherits(ProgressControl, _Component);
function ProgressControl() {
_classCallCheck(this, ProgressControl);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ProgressControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
};
return ProgressControl;
})(_componentJs2['default']);
ProgressControl.prototype.options_ = {
children: ['seekBar']
};
_componentJs2['default'].registerComponent('ProgressControl', ProgressControl);
exports['default'] = ProgressControl;
module.exports = exports['default'];
},{"../../component.js":65,"./mouse-time-display.js":74,"./seek-bar.js":77}],77:[function(_dereq_,module,exports){
/**
* @file seek-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _loadProgressBarJs = _dereq_('./load-progress-bar.js');
var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs);
var _playProgressBarJs = _dereq_('./play-progress-bar.js');
var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Seek Bar and holder for the progress bars
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class SeekBar
*/
var SeekBar = (function (_Slider) {
_inherits(SeekBar, _Slider);
function SeekBar(player, options) {
_classCallCheck(this, SeekBar);
_Slider.call(this, player, options);
this.on(player, 'timeupdate', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
SeekBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-holder'
}, {
'aria-label': 'video progress bar'
});
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete)
};
/**
* Get percentage of video played
*
* @return {Number} Percentage played
* @method getPercent
*/
SeekBar.prototype.getPercent = function getPercent() {
var percent = this.player_.currentTime() / this.player_.duration();
return percent >= 1 ? 1 : percent;
};
/**
* Handle mouse down on seek bar
*
* @method handleMouseDown
*/
SeekBar.prototype.handleMouseDown = function handleMouseDown(event) {
_Slider.prototype.handleMouseDown.call(this, event);
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
};
/**
* Handle mouse move on seek bar
*
* @method handleMouseMove
*/
SeekBar.prototype.handleMouseMove = function handleMouseMove(event) {
var newTime = this.calculateDistance(event) * this.player_.duration();
// Don't let video end while scrubbing.
if (newTime === this.player_.duration()) {
newTime = newTime - 0.1;
}
// Set new time (tell player to seek to new time)
this.player_.currentTime(newTime);
};
/**
* Handle mouse up on seek bar
*
* @method handleMouseUp
*/
SeekBar.prototype.handleMouseUp = function handleMouseUp(event) {
_Slider.prototype.handleMouseUp.call(this, event);
this.player_.scrubbing(false);
if (this.videoWasPlaying) {
this.player_.play();
}
};
/**
* Move more quickly fast forward for keyboard-only users
*
* @method stepForward
*/
SeekBar.prototype.stepForward = function stepForward() {
this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
};
/**
* Move more quickly rewind for keyboard-only users
*
* @method stepBack
*/
SeekBar.prototype.stepBack = function stepBack() {
this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
};
return SeekBar;
})(_sliderSliderJs2['default']);
SeekBar.prototype.options_ = {
children: ['loadProgressBar', 'mouseTimeDisplay', 'playProgressBar'],
'barName': 'playProgressBar'
};
SeekBar.prototype.playerEvent = 'timeupdate';
_componentJs2['default'].registerComponent('SeekBar', SeekBar);
exports['default'] = SeekBar;
module.exports = exports['default'];
},{"../../component.js":65,"../../slider/slider.js":110,"../../utils/fn.js":130,"../../utils/format-time.js":131,"./load-progress-bar.js":73,"./play-progress-bar.js":75,"object.assign":45}],78:[function(_dereq_,module,exports){
/**
* @file custom-control-spacer.js
*/
'use strict';
exports.__esModule = true;
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 _spacerJs = _dereq_('./spacer.js');
var _spacerJs2 = _interopRequireDefault(_spacerJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @extends Spacer
* @class CustomControlSpacer
*/
var CustomControlSpacer = (function (_Spacer) {
_inherits(CustomControlSpacer, _Spacer);
function CustomControlSpacer() {
_classCallCheck(this, CustomControlSpacer);
_Spacer.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CustomControlSpacer.prototype.createEl = function createEl() {
var el = _Spacer.prototype.createEl.call(this, {
className: this.buildCSSClass()
});
// No-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
el.innerHTML = ' ';
return el;
};
return CustomControlSpacer;
})(_spacerJs2['default']);
_componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer);
exports['default'] = CustomControlSpacer;
module.exports = exports['default'];
},{"../../component.js":65,"./spacer.js":79}],79:[function(_dereq_,module,exports){
/**
* @file spacer.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Just an empty spacer element that can be used as an append point for plugins, etc.
* Also can be used to create space between elements when necessary.
*
* @extends Component
* @class Spacer
*/
var Spacer = (function (_Component) {
_inherits(Spacer, _Component);
function Spacer() {
_classCallCheck(this, Spacer);
_Component.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Spacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Spacer.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
return Spacer;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Spacer', Spacer);
exports['default'] = Spacer;
module.exports = exports['default'];
},{"../../component.js":65}],80:[function(_dereq_,module,exports){
/**
* @file caption-settings-menu-item.js
*/
'use strict';
exports.__esModule = true;
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 _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The menu item for caption track settings menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class CaptionSettingsMenuItem
*/
var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) {
_inherits(CaptionSettingsMenuItem, _TextTrackMenuItem);
function CaptionSettingsMenuItem(player, options) {
_classCallCheck(this, CaptionSettingsMenuItem);
options['track'] = {
'kind': options['kind'],
'player': player,
'label': options['kind'] + ' settings',
'default': false,
mode: 'disabled'
};
_TextTrackMenuItem.call(this, player, options);
this.addClass('vjs-texttrack-settings');
}
/**
* Handle click on menu item
*
* @method handleClick
*/
CaptionSettingsMenuItem.prototype.handleClick = function handleClick() {
this.player().getChild('textTrackSettings').show();
};
return CaptionSettingsMenuItem;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
exports['default'] = CaptionSettingsMenuItem;
module.exports = exports['default'];
},{"../../component.js":65,"./text-track-menu-item.js":87}],81:[function(_dereq_,module,exports){
/**
* @file captions-button.js
*/
'use strict';
exports.__esModule = true;
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 _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js');
var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs);
/**
* The button component for toggling and selecting captions
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class CaptionsButton
*/
var CaptionsButton = (function (_TextTrackButton) {
_inherits(CaptionsButton, _TextTrackButton);
function CaptionsButton(player, options, ready) {
_classCallCheck(this, CaptionsButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Captions Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CaptionsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Update caption menu items
*
* @method update
*/
CaptionsButton.prototype.update = function update() {
var threshold = 2;
_TextTrackButton.prototype.update.call(this);
// if native, then threshold is 1 because no settings button
if (this.player().tech_ && this.player().tech_['featuresNativeTextTracks']) {
threshold = 1;
}
if (this.items && this.items.length > threshold) {
this.show();
} else {
this.hide();
}
};
/**
* Create caption menu items
*
* @return {Array} Array of menu items
* @method createItems
*/
CaptionsButton.prototype.createItems = function createItems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_['featuresNativeTextTracks'])) {
items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ }));
}
return _TextTrackButton.prototype.createItems.call(this, items);
};
return CaptionsButton;
})(_textTrackButtonJs2['default']);
CaptionsButton.prototype.kind_ = 'captions';
CaptionsButton.prototype.controlText_ = 'Captions';
_componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton);
exports['default'] = CaptionsButton;
module.exports = exports['default'];
},{"../../component.js":65,"./caption-settings-menu-item.js":80,"./text-track-button.js":86}],82:[function(_dereq_,module,exports){
/**
* @file chapters-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js');
var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* The button component for toggling and selecting chapters
* Chapters act much differently than other text tracks
* Cues are navigation vs. other tracks of alternative languages
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class ChaptersButton
*/
var ChaptersButton = (function (_TextTrackButton) {
_inherits(ChaptersButton, _TextTrackButton);
function ChaptersButton(player, options, ready) {
_classCallCheck(this, ChaptersButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Chapters Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
ChaptersButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Create a menu item for each text track
*
* @return {Array} Array of menu items
* @method createItems
*/
ChaptersButton.prototype.createItems = function createItems() {
var items = [];
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['kind'] === this.kind_) {
items.push(new _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
/**
* Create menu from chapter buttons
*
* @return {Menu} Menu of chapter buttons
* @method createMenu
*/
ChaptersButton.prototype.createMenu = function createMenu() {
var _this = this;
var tracks = this.player_.textTracks() || [];
var chaptersTrack = undefined;
var items = this.items = [];
for (var i = 0, _length = tracks.length; i < _length; i++) {
var track = tracks[i];
if (track['kind'] === this.kind_) {
chaptersTrack = track;
break;
}
}
var menu = this.menu;
if (menu === undefined) {
menu = new _menuMenuJs2['default'](this.player_);
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](this.kind_),
tabIndex: -1
}));
}
if (chaptersTrack && chaptersTrack.cues == null) {
chaptersTrack['mode'] = 'hidden';
var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(chaptersTrack);
if (remoteTextTrackEl) {
remoteTextTrackEl.addEventListener('load', function (event) {
return _this.update();
});
}
}
if (chaptersTrack && chaptersTrack.cues && chaptersTrack.cues.length > 0) {
var cues = chaptersTrack['cues'],
cue = undefined;
for (var i = 0, l = cues.length; i < l; i++) {
cue = cues[i];
var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, {
'track': chaptersTrack,
'cue': cue
});
items.push(mi);
menu.addChild(mi);
}
this.addChild(menu);
}
if (this.items.length > 0) {
this.show();
}
return menu;
};
return ChaptersButton;
})(_textTrackButtonJs2['default']);
ChaptersButton.prototype.kind_ = 'chapters';
ChaptersButton.prototype.controlText_ = 'Chapters';
_componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton);
exports['default'] = ChaptersButton;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu.js":104,"../../utils/dom.js":128,"../../utils/fn.js":130,"../../utils/to-title-case.js":137,"./chapters-track-menu-item.js":83,"./text-track-button.js":86,"./text-track-menu-item.js":87,"global/window":2}],83:[function(_dereq_,module,exports){
/**
* @file chapters-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
/**
* The chapter track menu item
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class ChaptersTrackMenuItem
*/
var ChaptersTrackMenuItem = (function (_MenuItem) {
_inherits(ChaptersTrackMenuItem, _MenuItem);
function ChaptersTrackMenuItem(player, options) {
_classCallCheck(this, ChaptersTrackMenuItem);
var track = options['track'];
var cue = options['cue'];
var currentTime = player.currentTime();
// Modify options for parent MenuItem class's init.
options['label'] = cue.text;
options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime'];
_MenuItem.call(this, player, options);
this.track = track;
this.cue = cue;
track.addEventListener('cuechange', Fn.bind(this, this.update));
}
/**
* Handle click on menu item
*
* @method handleClick
*/
ChaptersTrackMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
};
/**
* Update chapter menu item
*
* @method update
*/
ChaptersTrackMenuItem.prototype.update = function update() {
var cue = this.cue;
var currentTime = this.player_.currentTime();
// vjs.log(currentTime, cue.startTime);
this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']);
};
return ChaptersTrackMenuItem;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
exports['default'] = ChaptersTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu-item.js":103,"../../utils/fn.js":130}],84:[function(_dereq_,module,exports){
/**
* @file off-text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
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 _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* A special menu item for turning of a specific type of text track
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class OffTextTrackMenuItem
*/
var OffTextTrackMenuItem = (function (_TextTrackMenuItem) {
_inherits(OffTextTrackMenuItem, _TextTrackMenuItem);
function OffTextTrackMenuItem(player, options) {
_classCallCheck(this, OffTextTrackMenuItem);
// Create pseudo track info
// Requires options['kind']
options['track'] = {
'kind': options['kind'],
'player': player,
'label': options['kind'] + ' off',
'default': false,
'mode': 'disabled'
};
_TextTrackMenuItem.call(this, player, options);
this.selected(true);
}
/**
* Handle text track change
*
* @param {Object} event Event object
* @method handleTracksChange
*/
OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
var tracks = this.player().textTracks();
var selected = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') {
selected = false;
break;
}
}
this.selected(selected);
};
return OffTextTrackMenuItem;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
exports['default'] = OffTextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":65,"./text-track-menu-item.js":87}],85:[function(_dereq_,module,exports){
/**
* @file subtitles-button.js
*/
'use strict';
exports.__esModule = true;
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 _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The button component for toggling and selecting subtitles
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class SubtitlesButton
*/
var SubtitlesButton = (function (_TextTrackButton) {
_inherits(SubtitlesButton, _TextTrackButton);
function SubtitlesButton(player, options, ready) {
_classCallCheck(this, SubtitlesButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Subtitles Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
return SubtitlesButton;
})(_textTrackButtonJs2['default']);
SubtitlesButton.prototype.kind_ = 'subtitles';
SubtitlesButton.prototype.controlText_ = 'Subtitles';
_componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton);
exports['default'] = SubtitlesButton;
module.exports = exports['default'];
},{"../../component.js":65,"./text-track-button.js":86}],86:[function(_dereq_,module,exports){
/**
* @file text-track-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js');
var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs);
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class TextTrackButton
*/
var TextTrackButton = (function (_MenuButton) {
_inherits(TextTrackButton, _MenuButton);
function TextTrackButton(player, options) {
_classCallCheck(this, TextTrackButton);
_MenuButton.call(this, player, options);
var tracks = this.player_.textTracks();
if (this.items.length <= 1) {
this.hide();
}
if (!tracks) {
return;
}
var updateHandler = Fn.bind(this, this.update);
tracks.addEventListener('removetrack', updateHandler);
tracks.addEventListener('addtrack', updateHandler);
this.player_.on('dispose', function () {
tracks.removeEventListener('removetrack', updateHandler);
tracks.removeEventListener('addtrack', updateHandler);
});
}
// Create a menu item for each text track
TextTrackButton.prototype.createItems = function createItems() {
var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
// Add an OFF menu item to turn all tracks off
items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ }));
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// only add tracks that are of the appropriate kind and have a label
if (track['kind'] === this.kind_) {
items.push(new _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
return TextTrackButton;
})(_menuMenuButtonJs2['default']);
_componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton);
exports['default'] = TextTrackButton;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu-button.js":102,"../../utils/fn.js":130,"./off-text-track-menu-item.js":84,"./text-track-menu-item.js":87}],87:[function(_dereq_,module,exports){
/**
* @file text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* The specific menu item type for selecting a language within a text track kind
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class TextTrackMenuItem
*/
var TextTrackMenuItem = (function (_MenuItem) {
_inherits(TextTrackMenuItem, _MenuItem);
function TextTrackMenuItem(player, options) {
var _this = this;
_classCallCheck(this, TextTrackMenuItem);
var track = options['track'];
var tracks = player.textTracks();
// Modify options for parent MenuItem class's init.
options['label'] = track['label'] || track['language'] || 'Unknown';
options['selected'] = track['default'] || track['mode'] === 'showing';
_MenuItem.call(this, player, options);
this.track = track;
if (tracks) {
(function () {
var changeHandler = Fn.bind(_this, _this.handleTracksChange);
tracks.addEventListener('change', changeHandler);
_this.on('dispose', function () {
tracks.removeEventListener('change', changeHandler);
});
})();
}
// iOS7 doesn't dispatch change events to TextTrackLists when an
// associated track's mode changes. Without something like
// Object.observe() (also not present on iOS7), it's not
// possible to detect changes to the mode attribute and polyfill
// the change event. As a poor substitute, we manually dispatch
// change events whenever the controls modify the mode.
if (tracks && tracks.onchange === undefined) {
(function () {
var event = undefined;
_this.on(['tap', 'click'], function () {
if (typeof _globalWindow2['default'].Event !== 'object') {
// Android 2.3 throws an Illegal Constructor error for window.Event
try {
event = new _globalWindow2['default'].Event('change');
} catch (err) {}
}
if (!event) {
event = _globalDocument2['default'].createEvent('Event');
event.initEvent('change', true, true);
}
tracks.dispatchEvent(event);
});
})();
}
}
/**
* Handle click on text track
*
* @method handleClick
*/
TextTrackMenuItem.prototype.handleClick = function handleClick(event) {
var kind = this.track['kind'];
var tracks = this.player_.textTracks();
_MenuItem.prototype.handleClick.call(this, event);
if (!tracks) return;
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['kind'] !== kind) {
continue;
}
if (track === this.track) {
track['mode'] = 'showing';
} else {
track['mode'] = 'disabled';
}
}
};
/**
* Handle text track change
*
* @method handleTracksChange
*/
TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
this.selected(this.track['mode'] === 'showing');
};
return TextTrackMenuItem;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem);
exports['default'] = TextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":65,"../../menu/menu-item.js":103,"../../utils/fn.js":130,"global/document":1,"global/window":2}],88:[function(_dereq_,module,exports){
/**
* @file current-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the current time
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class CurrentTimeDisplay
*/
var CurrentTimeDisplay = (function (_Component) {
_inherits(CurrentTimeDisplay, _Component);
function CurrentTimeDisplay(player, options) {
_classCallCheck(this, CurrentTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CurrentTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-current-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-current-time-display',
// label the current time for screen reader users
innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update current time display
*
* @method updateContent
*/
CurrentTimeDisplay.prototype.updateContent = function updateContent() {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
var localizedText = this.localize('Current Time');
var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime;
};
return CurrentTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
exports['default'] = CurrentTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/dom.js":128,"../../utils/format-time.js":131}],89:[function(_dereq_,module,exports){
/**
* @file duration-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the duration
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class DurationDisplay
*/
var DurationDisplay = (function (_Component) {
_inherits(DurationDisplay, _Component);
function DurationDisplay(player, options) {
_classCallCheck(this, DurationDisplay);
_Component.call(this, player, options);
// this might need to be changed to 'durationchange' instead of 'timeupdate' eventually,
// however the durationchange event fires before this.player_.duration() is set,
// so the value cannot be written out using this method.
// Once the order of durationchange and this.player_.duration() being set is figured out,
// this can be updated.
this.on(player, 'timeupdate', this.updateContent);
this.on(player, 'loadedmetadata', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
DurationDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-duration vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-duration-display',
// label the duration time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update duration time display
*
* @method updateContent
*/
DurationDisplay.prototype.updateContent = function updateContent() {
var duration = this.player_.duration();
if (duration) {
var localizedText = this.localize('Duration Time');
var formattedTime = _utilsFormatTimeJs2['default'](duration);
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users
}
};
return DurationDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay);
exports['default'] = DurationDisplay;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/dom.js":128,"../../utils/format-time.js":131}],90:[function(_dereq_,module,exports){
/**
* @file remaining-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the time left in the video
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class RemainingTimeDisplay
*/
var RemainingTimeDisplay = (function (_Component) {
_inherits(RemainingTimeDisplay, _Component);
function RemainingTimeDisplay(player, options) {
_classCallCheck(this, RemainingTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
RemainingTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-remaining-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-remaining-time-display',
// label the remaining time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update remaining time display
*
* @method updateContent
*/
RemainingTimeDisplay.prototype.updateContent = function updateContent() {
if (this.player_.duration()) {
var localizedText = this.localize('Remaining Time');
var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime;
}
// Allows for smooth scrubbing, when player can't keep up.
// var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime();
// this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration());
};
return RemainingTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
exports['default'] = RemainingTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":65,"../../utils/dom.js":128,"../../utils/format-time.js":131}],91:[function(_dereq_,module,exports){
/**
* @file time-divider.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The separator between the current time and duration.
* Can be hidden if it's not needed in the design.
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class TimeDivider
*/
var TimeDivider = (function (_Component) {
_inherits(TimeDivider, _Component);
function TimeDivider() {
_classCallCheck(this, TimeDivider);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TimeDivider.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-control vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
};
return TimeDivider;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('TimeDivider', TimeDivider);
exports['default'] = TimeDivider;
module.exports = exports['default'];
},{"../../component.js":65}],92:[function(_dereq_,module,exports){
/**
* @file volume-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
// Required children
var _volumeLevelJs = _dereq_('./volume-level.js');
var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs);
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class VolumeBar
*/
var VolumeBar = (function (_Slider) {
_inherits(VolumeBar, _Slider);
function VolumeBar(player, options) {
_classCallCheck(this, VolumeBar);
_Slider.call(this, player, options);
this.on(player, 'volumechange', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-bar vjs-slider-bar'
}, {
'aria-label': 'volume level'
});
};
/**
* Handle mouse move on volume bar
*
* @method handleMouseMove
*/
VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) {
if (this.player_.muted()) {
this.player_.muted(false);
}
this.player_.volume(this.calculateDistance(event));
};
/**
* Get percent of volume level
*
* @retun {Number} Volume level percent
* @method getPercent
*/
VolumeBar.prototype.getPercent = function getPercent() {
if (this.player_.muted()) {
return 0;
} else {
return this.player_.volume();
}
};
/**
* Increase volume level for keyboard users
*
* @method stepForward
*/
VolumeBar.prototype.stepForward = function stepForward() {
this.player_.volume(this.player_.volume() + 0.1);
};
/**
* Decrease volume level for keyboard users
*
* @method stepBack
*/
VolumeBar.prototype.stepBack = function stepBack() {
this.player_.volume(this.player_.volume() - 0.1);
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current value of volume bar as a percentage
var volume = (this.player_.volume() * 100).toFixed(2);
this.el_.setAttribute('aria-valuenow', volume);
this.el_.setAttribute('aria-valuetext', volume + '%');
};
return VolumeBar;
})(_sliderSliderJs2['default']);
VolumeBar.prototype.options_ = {
children: ['volumeLevel'],
'barName': 'volumeLevel'
};
VolumeBar.prototype.playerEvent = 'volumechange';
_componentJs2['default'].registerComponent('VolumeBar', VolumeBar);
exports['default'] = VolumeBar;
module.exports = exports['default'];
},{"../../component.js":65,"../../slider/slider.js":110,"../../utils/fn.js":130,"./volume-level.js":94}],93:[function(_dereq_,module,exports){
/**
* @file volume-control.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _volumeBarJs = _dereq_('./volume-bar.js');
var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs);
/**
* The component for controlling the volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeControl
*/
var VolumeControl = (function (_Component) {
_inherits(VolumeControl, _Component);
function VolumeControl(player, options) {
_classCallCheck(this, VolumeControl);
_Component.call(this, player, options);
// hide volume controls when they're not supported by the current tech
if (player.tech_ && player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
}
this.on(player, 'loadstart', function () {
if (player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-control vjs-control'
});
};
return VolumeControl;
})(_componentJs2['default']);
VolumeControl.prototype.options_ = {
children: ['volumeBar']
};
_componentJs2['default'].registerComponent('VolumeControl', VolumeControl);
exports['default'] = VolumeControl;
module.exports = exports['default'];
},{"../../component.js":65,"./volume-bar.js":92}],94:[function(_dereq_,module,exports){
/**
* @file volume-level.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Shows volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeLevel
*/
var VolumeLevel = (function (_Component) {
_inherits(VolumeLevel, _Component);
function VolumeLevel() {
_classCallCheck(this, VolumeLevel);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeLevel.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
};
return VolumeLevel;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel);
exports['default'] = VolumeLevel;
module.exports = exports['default'];
},{"../../component.js":65}],95:[function(_dereq_,module,exports){
/**
* @file volume-menu-button.js
*/
'use strict';
exports.__esModule = true;
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 _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js');
var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs);
/**
* Button for volume menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class VolumeMenuButton
*/
var VolumeMenuButton = (function (_MenuButton) {
_inherits(VolumeMenuButton, _MenuButton);
function VolumeMenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, VolumeMenuButton);
// Default to inline
if (options.inline === undefined) {
options.inline = true;
}
// If the vertical option isn't passed at all, default to true.
if (options.vertical === undefined) {
// If an inline volumeMenuButton is used, we should default to using
// a horizontal slider for obvious reasons.
if (options.inline) {
options.vertical = false;
} else {
options.vertical = true;
}
}
// The vertical option needs to be set on the volumeBar as well,
// since that will need to be passed along to the VolumeBar constructor
options.volumeBar = options.volumeBar || {};
options.volumeBar.vertical = !!options.vertical;
_MenuButton.call(this, player, options);
// Same listeners as MuteToggle
this.on(player, 'volumechange', this.volumeUpdate);
this.on(player, 'loadstart', this.volumeUpdate);
// hide mute toggle if the current tech doesn't support volume control
function updateVisibility() {
if (player.tech_ && player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}
updateVisibility.call(this);
this.on(player, 'loadstart', updateVisibility);
this.on(this.volumeBar, ['slideractive', 'focus'], function () {
this.addClass('vjs-slider-active');
});
this.on(this.volumeBar, ['sliderinactive', 'blur'], function () {
this.removeClass('vjs-slider-active');
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() {
var orientationClass = '';
if (!!this.options_.vertical) {
orientationClass = 'vjs-volume-menu-button-vertical';
} else {
orientationClass = 'vjs-volume-menu-button-horizontal';
}
return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass;
};
/**
* Allow sub components to stack CSS class names
*
* @return {Menu} The volume menu button
* @method createMenu
*/
VolumeMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player_, {
contentElType: 'div'
});
var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar);
menu.addChild(vb);
this.volumeBar = vb;
return menu;
};
/**
* Handle click on volume menu and calls super
*
* @method handleClick
*/
VolumeMenuButton.prototype.handleClick = function handleClick() {
_muteToggleJs2['default'].prototype.handleClick.call(this);
_MenuButton.prototype.handleClick.call(this);
};
return VolumeMenuButton;
})(_menuMenuButtonJs2['default']);
VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update;
VolumeMenuButton.prototype.controlText_ = 'Mute';
_componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton);
exports['default'] = VolumeMenuButton;
module.exports = exports['default'];
},{"../button.js":63,"../component.js":65,"../menu/menu-button.js":102,"../menu/menu.js":104,"./mute-toggle.js":69,"./volume-control/volume-bar.js":92}],96:[function(_dereq_,module,exports){
/**
* @file error-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _modalDialog = _dereq_('./modal-dialog');
var _modalDialog2 = _interopRequireDefault(_modalDialog);
var _utilsDom = _dereq_('./utils/dom');
var Dom = _interopRequireWildcard(_utilsDom);
var _utilsMergeOptions = _dereq_('./utils/merge-options');
var _utilsMergeOptions2 = _interopRequireDefault(_utilsMergeOptions);
/**
* Display that an error has occurred making the video unplayable.
*
* @extends ModalDialog
* @class ErrorDisplay
*/
var ErrorDisplay = (function (_ModalDialog) {
_inherits(ErrorDisplay, _ModalDialog);
/**
* Constructor for error display modal.
*
* @param {Player} player
* @param {Object} [options]
*/
function ErrorDisplay(player, options) {
_classCallCheck(this, ErrorDisplay);
_ModalDialog.call(this, player, options);
this.on(player, 'error', this.open);
}
/**
* Include the old class for backward-compatibility.
*
* This can be removed in 6.0.
*
* @method buildCSSClass
* @deprecated
* @return {String}
*/
ErrorDisplay.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-error-display ' + _ModalDialog.prototype.buildCSSClass.call(this);
};
/**
* Generates the modal content based on the player error.
*
* @return {String|Null}
*/
ErrorDisplay.prototype.content = function content() {
var error = this.player().error();
return error ? this.localize(error.message) : '';
};
return ErrorDisplay;
})(_modalDialog2['default']);
ErrorDisplay.prototype.options_ = _utilsMergeOptions2['default'](_modalDialog2['default'].prototype.options_, {
fillAlways: true,
uncloseable: true
});
_component2['default'].registerComponent('ErrorDisplay', ErrorDisplay);
exports['default'] = ErrorDisplay;
module.exports = exports['default'];
},{"./component":65,"./modal-dialog":105,"./utils/dom":128,"./utils/merge-options":134}],97:[function(_dereq_,module,exports){
/**
* @file event-target.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var EventTarget = function EventTarget() {};
EventTarget.prototype.allowedEvents_ = {};
EventTarget.prototype.on = function (type, fn) {
// Remove the addEventListener alias before calling Events.on
// so we don't get into an infinite type loop
var ael = this.addEventListener;
this.addEventListener = Function.prototype;
Events.on(this, type, fn);
this.addEventListener = ael;
};
EventTarget.prototype.addEventListener = EventTarget.prototype.on;
EventTarget.prototype.off = function (type, fn) {
Events.off(this, type, fn);
};
EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
EventTarget.prototype.one = function (type, fn) {
Events.one(this, type, fn);
};
EventTarget.prototype.trigger = function (event) {
var type = event.type || event;
if (typeof event === 'string') {
event = {
type: type
};
}
event = Events.fixEvent(event);
if (this.allowedEvents_[type] && this['on' + type]) {
this['on' + type](event);
}
Events.trigger(this, event);
};
// The standard DOM EventTarget.dispatchEvent() is aliased to trigger()
EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
exports['default'] = EventTarget;
module.exports = exports['default'];
},{"./utils/events.js":129}],98:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsLog = _dereq_('./utils/log');
var _utilsLog2 = _interopRequireDefault(_utilsLog);
/*
* @file extend.js
*
* A combination of node inherits and babel's inherits (after transpile).
* Both work the same but node adds `super_` to the subClass
* and Bable adds the superClass as __proto__. Both seem useful.
*/
var _inherits = 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) {
// node
subClass.super_ = superClass;
}
};
/*
* Function for subclassing using the same inheritance that
* videojs uses internally
* ```js
* var Button = videojs.getComponent('Button');
* ```
* ```js
* var MyButton = videojs.extend(Button, {
* constructor: function(player, options) {
* Button.call(this, player, options);
* },
* onClick: function() {
* // doSomething
* }
* });
* ```
*/
var extendFn = function extendFn(superClass) {
var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var subClass = function subClass() {
superClass.apply(this, arguments);
};
var methods = {};
if (typeof subClassMethods === 'object') {
if (typeof subClassMethods.init === 'function') {
_utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.');
subClassMethods.constructor = subClassMethods.init;
}
if (subClassMethods.constructor !== Object.prototype.constructor) {
subClass = subClassMethods.constructor;
}
methods = subClassMethods;
} else if (typeof subClassMethods === 'function') {
subClass = subClassMethods;
}
_inherits(subClass, superClass);
// Extend subObj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasOwnProperty(name)) {
subClass.prototype[name] = methods[name];
}
}
return subClass;
};
exports['default'] = extendFn;
module.exports = exports['default'];
},{"./utils/log":133}],99:[function(_dereq_,module,exports){
/**
* @file fullscreen-api.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* Store the browser-specific methods for the fullscreen API
* @type {Object|undefined}
* @private
*/
var FullscreenApi = {};
// browser API methods
// map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js
var apiMap = [
// Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'],
// WebKit
['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Old WebKit (Safari 5.1)
['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Mozilla
['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'],
// Microsoft
['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']];
var specApi = apiMap[0];
var browserApi = undefined;
// determine the supported set of functions
for (var i = 0; i < apiMap.length; i++) {
// check for exitFullscreen function
if (apiMap[i][1] in _globalDocument2['default']) {
browserApi = apiMap[i];
break;
}
}
// map the browser API names to the spec API names
if (browserApi) {
for (var i = 0; i < browserApi.length; i++) {
FullscreenApi[specApi[i]] = browserApi[i];
}
}
exports['default'] = FullscreenApi;
module.exports = exports['default'];
},{"global/document":1}],100:[function(_dereq_,module,exports){
/**
* @file loading-spinner.js
*/
'use strict';
exports.__esModule = true;
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 _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
/* Loading Spinner
================================================================================ */
/**
* Loading spinner for waiting events
*
* @extends Component
* @class LoadingSpinner
*/
var LoadingSpinner = (function (_Component) {
_inherits(LoadingSpinner, _Component);
function LoadingSpinner() {
_classCallCheck(this, LoadingSpinner);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @method createEl
*/
LoadingSpinner.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-loading-spinner'
});
};
return LoadingSpinner;
})(_component2['default']);
_component2['default'].registerComponent('LoadingSpinner', LoadingSpinner);
exports['default'] = LoadingSpinner;
module.exports = exports['default'];
},{"./component":65}],101:[function(_dereq_,module,exports){
/**
* @file media-error.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/*
* Custom MediaError to mimic the HTML5 MediaError
*
* @param {Number} code The media error code
*/
var MediaError = function MediaError(code) {
if (typeof code === 'number') {
this.code = code;
} else if (typeof code === 'string') {
// default code is zero, so this is a custom error
this.message = code;
} else if (typeof code === 'object') {
// object
_objectAssign2['default'](this, code);
}
if (!this.message) {
this.message = MediaError.defaultMessages[this.code] || '';
}
};
/*
* The error code that refers two one of the defined
* MediaError types
*
* @type {Number}
*/
MediaError.prototype.code = 0;
/*
* An optional message to be shown with the error.
* Message is not part of the HTML5 video spec
* but allows for more informative custom errors.
*
* @type {String}
*/
MediaError.prototype.message = '';
/*
* An optional status code that can be set by plugins
* to allow even more detail about the error.
* For example the HLS plugin might provide the specific
* HTTP status code that was returned when the error
* occurred, then allowing a custom error overlay
* to display more information.
*
* @type {Array}
*/
MediaError.prototype.status = null;
MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0
'MEDIA_ERR_ABORTED', // = 1
'MEDIA_ERR_NETWORK', // = 2
'MEDIA_ERR_DECODE', // = 3
'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4
'MEDIA_ERR_ENCRYPTED' // = 5
];
MediaError.defaultMessages = {
1: 'You aborted the media playback',
2: 'A network error caused the media download to fail part-way.',
3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The media is encrypted and we do not have the keys to decrypt it.'
};
// Add types as properties on MediaError
// e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
MediaError[MediaError.errorTypes[errNum]] = errNum;
// values should be accessible on both the class and instance
MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
}
exports['default'] = MediaError;
module.exports = exports['default'];
},{"object.assign":45}],102:[function(_dereq_,module,exports){
/**
* @file menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuJs = _dereq_('./menu.js');
var _menuJs2 = _interopRequireDefault(_menuJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* A button class with a popup menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuButton
*/
var MenuButton = (function (_Button) {
_inherits(MenuButton, _Button);
function MenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, MenuButton);
_Button.call(this, player, options);
this.update();
this.on('keydown', this.handleKeyPress);
this.el_.setAttribute('aria-haspopup', true);
this.el_.setAttribute('role', 'button');
}
/**
* Update menu
*
* @method update
*/
MenuButton.prototype.update = function update() {
var menu = this.createMenu();
if (this.menu) {
this.removeChild(this.menu);
}
this.menu = menu;
this.addChild(menu);
/**
* Track the state of the menu button
*
* @type {Boolean}
* @private
*/
this.buttonPressed_ = false;
if (this.items && this.items.length === 0) {
this.hide();
} else if (this.items && this.items.length > 1) {
this.show();
}
};
/**
* Create menu
*
* @return {Menu} The constructed menu
* @method createMenu
*/
MenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuJs2['default'](this.player_);
// Add a title list item to the top
if (this.options_.title) {
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](this.options_.title),
tabIndex: -1
}));
}
this.items = this['createItems']();
if (this.items) {
// Add menu items to the menu
for (var i = 0; i < this.items.length; i++) {
menu.addItem(this.items[i]);
}
}
return menu;
};
/**
* Create the list of menu items. Specific to each subclass.
*
* @method createItems
*/
MenuButton.prototype.createItems = function createItems() {};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MenuButton.prototype.createEl = function createEl() {
return _Button.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MenuButton.prototype.buildCSSClass = function buildCSSClass() {
var menuButtonClass = 'vjs-menu-button';
// If the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menuButtonClass += '-inline';
} else {
menuButtonClass += '-popup';
}
return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Focus - Add keyboard functionality to element
* This function is not needed anymore. Instead, the
* keyboard functionality is handled by
* treating the button as triggering a submenu.
* When the button is pressed, the submenu
* appears. Pressing the button again makes
* the submenu disappear.
*
* @method handleFocus
*/
MenuButton.prototype.handleFocus = function handleFocus() {};
/**
* Can't turn off list display that we turned
* on with focus, because list would go away.
*
* @method handleBlur
*/
MenuButton.prototype.handleBlur = function handleBlur() {};
/**
* When you click the button it adds focus, which
* will show the menu indefinitely.
* So we'll remove focus when the mouse leaves the button.
* Focus is needed for tab navigation.
* Allow sub components to stack CSS class names
*
* @method handleClick
*/
MenuButton.prototype.handleClick = function handleClick() {
this.one('mouseout', Fn.bind(this, function () {
this.menu.unlockShowing();
this.el_.blur();
}));
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
};
/**
* Handle key press on menu
*
* @param {Object} Key press event
* @method handleKeyPress
*/
MenuButton.prototype.handleKeyPress = function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which === 32 || event.which === 13) {
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
event.preventDefault();
// Check for escape (27) key
} else if (event.which === 27) {
if (this.buttonPressed_) {
this.unpressButton();
}
event.preventDefault();
}
};
/**
* Makes changes based on button pressed
*
* @method pressButton
*/
MenuButton.prototype.pressButton = function pressButton() {
this.buttonPressed_ = true;
this.menu.lockShowing();
this.el_.setAttribute('aria-pressed', true);
if (this.items && this.items.length > 0) {
this.items[0].el().focus(); // set the focus to the title of the submenu
}
};
/**
* Makes changes based on button unpressed
*
* @method unpressButton
*/
MenuButton.prototype.unpressButton = function unpressButton() {
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.el_.setAttribute('aria-pressed', false);
};
return MenuButton;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuButton', MenuButton);
exports['default'] = MenuButton;
module.exports = exports['default'];
},{"../button.js":63,"../component.js":65,"../utils/dom.js":128,"../utils/fn.js":130,"../utils/to-title-case.js":137,"./menu.js":104}],103:[function(_dereq_,module,exports){
/**
* @file menu-item.js
*/
'use strict';
exports.__esModule = true;
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 _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The component for a menu item. `<li>`
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuItem
*/
var MenuItem = (function (_Button) {
_inherits(MenuItem, _Button);
function MenuItem(player, options) {
_classCallCheck(this, MenuItem);
_Button.call(this, player, options);
this.selected(options['selected']);
}
/**
* Create the component's DOM element
*
* @param {String=} type Desc
* @param {Object=} props Desc
* @return {Element}
* @method createEl
*/
MenuItem.prototype.createEl = function createEl(type, props, attrs) {
return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({
className: 'vjs-menu-item',
innerHTML: this.localize(this.options_['label'])
}, props), attrs);
};
/**
* Handle a click on the menu item, and set it to selected
*
* @method handleClick
*/
MenuItem.prototype.handleClick = function handleClick() {
this.selected(true);
};
/**
* Set this menu item as selected or not
*
* @param {Boolean} selected
* @method selected
*/
MenuItem.prototype.selected = function selected(_selected) {
if (_selected) {
this.addClass('vjs-selected');
this.el_.setAttribute('aria-selected', true);
} else {
this.removeClass('vjs-selected');
this.el_.setAttribute('aria-selected', false);
}
};
return MenuItem;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuItem', MenuItem);
exports['default'] = MenuItem;
module.exports = exports['default'];
},{"../button.js":63,"../component.js":65,"object.assign":45}],104:[function(_dereq_,module,exports){
/**
* @file menu.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
/**
* The Menu component is used to build pop up menus, including subtitle and
* captions selection menus.
*
* @extends Component
* @class Menu
*/
var Menu = (function (_Component) {
_inherits(Menu, _Component);
function Menu() {
_classCallCheck(this, Menu);
_Component.apply(this, arguments);
}
/**
* Add a menu item to the menu
*
* @param {Object|String} component Component or component type to add
* @method addItem
*/
Menu.prototype.addItem = function addItem(component) {
this.addChild(component);
component.on('click', Fn.bind(this, function () {
this.unlockShowing();
}));
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Menu.prototype.createEl = function createEl() {
var contentElType = this.options_.contentElType || 'ul';
this.contentEl_ = Dom.createEl(contentElType, {
className: 'vjs-menu-content'
});
var el = _Component.prototype.createEl.call(this, 'div', {
append: this.contentEl_,
className: 'vjs-menu'
});
el.appendChild(this.contentEl_);
// Prevent clicks from bubbling up. Needed for Menu Buttons,
// where a click on the parent is significant
Events.on(el, 'click', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
return el;
};
return Menu;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Menu', Menu);
exports['default'] = Menu;
module.exports = exports['default'];
},{"../component.js":65,"../utils/dom.js":128,"../utils/events.js":129,"../utils/fn.js":130}],105:[function(_dereq_,module,exports){
/**
* @file modal-dialog.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _utilsDom = _dereq_('./utils/dom');
var Dom = _interopRequireWildcard(_utilsDom);
var _utilsFn = _dereq_('./utils/fn');
var Fn = _interopRequireWildcard(_utilsFn);
var _utilsLog = _dereq_('./utils/log');
var _utilsLog2 = _interopRequireDefault(_utilsLog);
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _closeButton = _dereq_('./close-button');
var _closeButton2 = _interopRequireDefault(_closeButton);
var MODAL_CLASS_NAME = 'vjs-modal-dialog';
var ESC = 27;
/**
* The `ModalDialog` displays over the video and its controls, which blocks
* interaction with the player until it is closed.
*
* Modal dialogs include a "Close" button and will close when that button
* is activated - or when ESC is pressed anywhere.
*
* @extends Component
* @class ModalDialog
*/
var ModalDialog = (function (_Component) {
_inherits(ModalDialog, _Component);
/**
* Constructor for modals.
*
* @param {Player} player
* @param {Object} [options]
* @param {Mixed} [options.content=undefined]
* Provide customized content for this modal.
*
* @param {String} [options.description]
* A text description for the modal, primarily for accessibility.
*
* @param {Boolean} [options.fillAlways=false]
* Normally, modals are automatically filled only the first time
* they open. This tells the modal to refresh its content
* every time it opens.
*
* @param {String} [options.label]
* A text label for the modal, primarily for accessibility.
*
* @param {Boolean} [options.temporary=true]
* If `true`, the modal can only be opened once; it will be
* disposed as soon as it's closed.
*
* @param {Boolean} [options.uncloseable=false]
* If `true`, the user will not be able to close the modal
* through the UI in the normal ways. Programmatic closing is
* still possible.
*
*/
function ModalDialog(player, options) {
_classCallCheck(this, ModalDialog);
_Component.call(this, player, options);
this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
this.closeable(!this.options_.uncloseable);
this.content(this.options_.content);
// Make sure the contentEl is defined AFTER any children are initialized
// because we only want the contents of the modal in the contentEl
// (not the UI elements like the close button).
this.contentEl_ = Dom.createEl('div', {
className: MODAL_CLASS_NAME + '-content'
}, {
role: 'document'
});
this.descEl_ = Dom.createEl('p', {
className: MODAL_CLASS_NAME + '-description vjs-offscreen',
id: this.el().getAttribute('aria-describedby')
});
Dom.textContent(this.descEl_, this.description());
this.el_.appendChild(this.descEl_);
this.el_.appendChild(this.contentEl_);
}
/*
* Modal dialog default options.
*
* @type {Object}
* @private
*/
/**
* Create the modal's DOM element
*
* @method createEl
* @return {Element}
*/
ModalDialog.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass(),
tabIndex: -1
}, {
'aria-describedby': this.id() + '_description',
'aria-hidden': 'true',
'aria-label': this.label(),
role: 'dialog'
});
};
/**
* Build the modal's CSS class.
*
* @method buildCSSClass
* @return {String}
*/
ModalDialog.prototype.buildCSSClass = function buildCSSClass() {
return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Handles key presses on the document, looking for ESC, which closes
* the modal.
*
* @method handleKeyPress
* @param {Event} e
*/
ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) {
if (e.which === ESC && this.closeable()) {
this.close();
}
};
/**
* Returns the label string for this modal. Primarily used for accessibility.
*
* @return {String}
*/
ModalDialog.prototype.label = function label() {
return this.options_.label || this.localize('Modal Window');
};
/**
* Returns the description string for this modal. Primarily used for
* accessibility.
*
* @return {String}
*/
ModalDialog.prototype.description = function description() {
var desc = this.options_.description || this.localize('This is a modal window.');
// Append a universal closeability message if the modal is closeable.
if (this.closeable()) {
desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
}
return desc;
};
/**
* Opens the modal.
*
* @method open
* @return {ModalDialog}
*/
ModalDialog.prototype.open = function open() {
if (!this.opened_) {
var player = this.player();
this.trigger('beforemodalopen');
this.opened_ = true;
// Fill content if the modal has never opened before and
// never been filled.
if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
this.fill();
}
// If the player was playing, pause it and take note of its previously
// playing state.
this.wasPlaying_ = !player.paused();
if (this.wasPlaying_) {
player.pause();
}
if (this.closeable()) {
this.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
}
player.controls(false);
this.show();
this.el().setAttribute('aria-hidden', 'false');
this.trigger('modalopen');
this.hasBeenOpened_ = true;
}
return this;
};
/**
* Whether or not the modal is opened currently.
*
* @method opened
* @param {Boolean} [value]
* If given, it will open (`true`) or close (`false`) the modal.
*
* @return {Boolean}
*/
ModalDialog.prototype.opened = function opened(value) {
if (typeof value === 'boolean') {
this[value ? 'open' : 'close']();
}
return this.opened_;
};
/**
* Closes the modal.
*
* @method close
* @return {ModalDialog}
*/
ModalDialog.prototype.close = function close() {
if (this.opened_) {
var player = this.player();
this.trigger('beforemodalclose');
this.opened_ = false;
if (this.wasPlaying_) {
player.play();
}
if (this.closeable()) {
this.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
}
player.controls(true);
this.hide();
this.el().setAttribute('aria-hidden', 'true');
this.trigger('modalclose');
if (this.options_.temporary) {
this.dispose();
}
}
return this;
};
/**
* Whether or not the modal is closeable via the UI.
*
* @method closeable
* @param {Boolean} [value]
* If given as a Boolean, it will set the `closeable` option.
*
* @return {Boolean}
*/
ModalDialog.prototype.closeable = function closeable(value) {
if (typeof value === 'boolean') {
var closeable = this.closeable_ = !!value;
var _close = this.getChild('closeButton');
// If this is being made closeable and has no close button, add one.
if (closeable && !_close) {
// The close button should be a child of the modal - not its
// content element, so temporarily change the content element.
var temp = this.contentEl_;
this.contentEl_ = this.el_;
_close = this.addChild('closeButton');
this.contentEl_ = temp;
this.on(_close, 'close', this.close);
}
// If this is being made uncloseable and has a close button, remove it.
if (!closeable && _close) {
this.off(_close, 'close', this.close);
this.removeChild(_close);
_close.dispose();
}
}
return this.closeable_;
};
/**
* Fill the modal's content element with the modal's "content" option.
*
* The content element will be emptied before this change takes place.
*
* @method fill
* @return {ModalDialog}
*/
ModalDialog.prototype.fill = function fill() {
return this.fillWith(this.content());
};
/**
* Fill the modal's content element with arbitrary content.
*
* The content element will be emptied before this change takes place.
*
* @method fillWith
* @param {Mixed} [content]
* The same rules apply to this as apply to the `content` option.
*
* @return {ModalDialog}
*/
ModalDialog.prototype.fillWith = function fillWith(content) {
var contentEl = this.contentEl();
var parentEl = contentEl.parentNode;
var nextSiblingEl = contentEl.nextSibling;
this.trigger('beforemodalfill');
this.hasBeenFilled_ = true;
// Detach the content element from the DOM before performing
// manipulation to avoid modifying the live DOM multiple times.
parentEl.removeChild(contentEl);
this.empty();
Dom.insertContent(contentEl, content);
this.trigger('modalfill');
// Re-inject the re-filled content element.
if (nextSiblingEl) {
parentEl.insertBefore(contentEl, nextSiblingEl);
} else {
parentEl.appendChild(contentEl);
}
return this;
};
/**
* Empties the content element.
*
* This happens automatically anytime the modal is filled.
*
* @method empty
* @return {ModalDialog}
*/
ModalDialog.prototype.empty = function empty() {
this.trigger('beforemodalempty');
Dom.emptyEl(this.contentEl());
this.trigger('modalempty');
return this;
};
/**
* Gets or sets the modal content, which gets normalized before being
* rendered into the DOM.
*
* This does not update the DOM or fill the modal, but it is called during
* that process.
*
* @method content
* @param {Mixed} [value]
* If defined, sets the internal content value to be used on the
* next call(s) to `fill`. This value is normalized before being
* inserted. To "clear" the internal content value, pass `null`.
*
* @return {Mixed}
*/
ModalDialog.prototype.content = function content(value) {
if (typeof value !== 'undefined') {
this.content_ = value;
}
return this.content_;
};
return ModalDialog;
})(_component2['default']);
ModalDialog.prototype.options_ = {
temporary: true
};
_component2['default'].registerComponent('ModalDialog', ModalDialog);
exports['default'] = ModalDialog;
module.exports = exports['default'];
},{"./close-button":64,"./component":65,"./utils/dom":128,"./utils/fn":130,"./utils/log":133,"global/document":1}],106:[function(_dereq_,module,exports){
/**
* @file player.js
*/
// Subclasses Component
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsBufferJs = _dereq_('./utils/buffer.js');
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _fullscreenApiJs = _dereq_('./fullscreen-api.js');
var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs);
var _mediaErrorJs = _dereq_('./media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js');
var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs);
// Include required child components (importing also registers them)
var _techLoaderJs = _dereq_('./tech/loader.js');
var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs);
var _posterImageJs = _dereq_('./poster-image.js');
var _posterImageJs2 = _interopRequireDefault(_posterImageJs);
var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js');
var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs);
var _loadingSpinnerJs = _dereq_('./loading-spinner.js');
var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs);
var _bigPlayButtonJs = _dereq_('./big-play-button.js');
var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs);
var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js');
var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs);
var _errorDisplayJs = _dereq_('./error-display.js');
var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs);
var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js');
var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs);
var _modalDialog = _dereq_('./modal-dialog');
var _modalDialog2 = _interopRequireDefault(_modalDialog);
// Require html5 tech, at least for disposing the original video tag
var _techTechJs = _dereq_('./tech/tech.js');
var _techTechJs2 = _interopRequireDefault(_techTechJs);
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
/**
* An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video.
* ```js
* var myPlayer = videojs('example_video_1');
* ```
* In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready.
* ```html
* <video id="example_video_1" data-setup='{}' controls>
* <source src="my-source.mp4" type="video/mp4">
* </video>
* ```
* After an instance has been created it can be accessed globally using `Video('example_video_1')`.
*
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class Player
*/
var Player = (function (_Component) {
_inherits(Player, _Component);
/**
* player's constructor function
*
* @constructs
* @method init
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Player options
* @param {Function=} ready Ready callback function
*/
function Player(tag, options, ready) {
var _this = this;
_classCallCheck(this, Player);
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + Guid.newGUID();
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = _objectAssign2['default'](Player.getTagSettings(tag), options);
// Delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initChildren = false;
// Same with creating the element
options.createEl = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// Run base component initializing with new options
_Component.call(this, null, options, ready);
// if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
}
this.tag = tag; // Store the original tag used to set options
// Store the tag attributes used to restore html5 element
this.tagAttributes = tag && Dom.getElAttributes(tag);
// Update current language
this.language(this.options_.language);
// Update Supported Languages
if (options.languages) {
(function () {
// Normalise player option languages to lowercase
var languagesToLower = {};
Object.getOwnPropertyNames(options.languages).forEach(function (name) {
languagesToLower[name.toLowerCase()] = options.languages[name];
});
_this.languages_ = languagesToLower;
})();
} else {
this.languages_ = Player.prototype.options_.languages;
}
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options.poster || '';
// Set controls
this.controls_ = !!options.controls;
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
/*
* Store the internal state of scrubbing
*
* @private
* @return {Boolean} True if the user is scrubbing
*/
this.scrubbing_ = false;
this.el_ = this.createEl();
// We also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// We also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_);
// Load plugins
if (options.plugins) {
(function () {
var plugins = options.plugins;
Object.getOwnPropertyNames(plugins).forEach(function (name) {
if (typeof this[name] === 'function') {
this[name](plugins[name]);
} else {
_utilsLogJs2['default'].error('Unable to find plugin:', name);
}
}, _this);
})();
}
this.options_.playerOptions = playerOptionsCopy;
this.initChildren();
// Set isAudio based on whether or not an audio tag was used
this.isAudio(tag.nodeName.toLowerCase() === 'audio');
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
if (this.isAudio()) {
this.addClass('vjs-audio');
}
if (this.flexNotSupported_()) {
this.addClass('vjs-no-flex');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (browser.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Make player easily findable by ID
Player.players[this.id_] = this;
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
this.userActive(true);
this.reportUserActivity();
this.listenForUserActivity_();
this.on('fullscreenchange', this.handleFullscreenChange_);
this.on('stageclick', this.handleStageClick_);
}
/*
* Global player list
*
* @type {Object}
*/
/**
* Destroys the video player and does any necessary cleanup
* ```js
* myPlayer.dispose();
* ```
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*
* @method dispose
*/
Player.prototype.dispose = function dispose() {
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
if (this.styleEl_) {
this.styleEl_.parentNode.removeChild(this.styleEl_);
}
// Kill reference to this player
Player.players[this.id_] = null;
if (this.tag && this.tag.player) {
this.tag.player = null;
}
if (this.el_ && this.el_.player) {
this.el_.player = null;
}
if (this.tech_) {
this.tech_.dispose();
}
_Component.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Player.prototype.createEl = function createEl() {
var el = this.el_ = _Component.prototype.createEl.call(this, 'div');
var tag = this.tag;
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
var attrs = Dom.getElAttributes(tag);
Object.getOwnPropertyNames(attrs).forEach(function (attr) {
// workaround so we don't totally break IE7
// http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7
if (attr === 'class') {
el.className = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
});
// Update tag id/class for use as HTML5 playback tech
// Might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.id += '_html5_api';
tag.className = 'vjs-tech';
// Make player findable on elements
tag.player = el.player = this;
// Default state of video is paused
this.addClass('vjs-paused');
// Add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overrideable by CSS, just like the
// video element
this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions');
var defaultsStyleEl = Dom.$('.vjs-styles-defaults');
var head = Dom.$('head');
head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
// Pass in the width/height/aspectRatio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fluid(this.options_.fluid);
this.aspectRatio(this.options_.aspectRatio);
// insertElFirst seems to cause the networkState to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initNetworkState_ = tag.networkState;
// Wrap video tag in div (el/box) container
if (tag.parentNode) {
tag.parentNode.insertBefore(el, tag);
}
Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
this.el_ = el;
return el;
};
/**
* Get/set player width
*
* @param {Number=} value Value for width
* @return {Number} Width when getting
* @method width
*/
Player.prototype.width = function width(value) {
return this.dimension('width', value);
};
/**
* Get/set player height
*
* @param {Number=} value Value for height
* @return {Number} Height when getting
* @method height
*/
Player.prototype.height = function height(value) {
return this.dimension('height', value);
};
/**
* Get/set dimension for player
*
* @param {String} dimension Either width or height
* @param {Number=} value Value for dimension
* @return {Component}
* @method dimension
*/
Player.prototype.dimension = function dimension(_dimension, value) {
var privDimension = _dimension + '_';
if (value === undefined) {
return this[privDimension] || 0;
}
if (value === '') {
// If an empty string is given, reset the dimension to be automatic
this[privDimension] = undefined;
} else {
var parsedVal = parseFloat(value);
if (isNaN(parsedVal)) {
_utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension);
return this;
}
this[privDimension] = parsedVal;
}
this.updateStyleEl_();
return this;
};
/**
* Add/remove the vjs-fluid class
*
* @param {Boolean} bool Value of true adds the class, value of false removes the class
* @method fluid
*/
Player.prototype.fluid = function fluid(bool) {
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (bool) {
this.addClass('vjs-fluid');
} else {
this.removeClass('vjs-fluid');
}
};
/**
* Get/Set the aspect ratio
*
* @param {String=} ratio Aspect ratio for player
* @return aspectRatio
* @method aspectRatio
*/
Player.prototype.aspectRatio = function aspectRatio(ratio) {
if (ratio === undefined) {
return this.aspectRatio_;
}
// Check for width:height format
if (!/^\d+\:\d+$/.test(ratio)) {
throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
}
this.aspectRatio_ = ratio;
// We're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updateStyleEl_();
};
/**
* Update styles of the player element (height, width and aspect ratio)
*
* @method updateStyleEl_
*/
Player.prototype.updateStyleEl_ = function updateStyleEl_() {
var width = undefined;
var height = undefined;
var aspectRatio = undefined;
var idClass = undefined;
// The aspect ratio is either used directly or to calculate width and height.
if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
// Use any aspectRatio that's been specifically set
aspectRatio = this.aspectRatio_;
} else if (this.videoWidth()) {
// Otherwise try to get the aspect ratio from the video metadata
aspectRatio = this.videoWidth() + ':' + this.videoHeight();
} else {
// Or use a default. The video element's is 2:1, but 16:9 is more common.
aspectRatio = '16:9';
}
// Get the ratio as a decimal we can use to calculate dimensions
var ratioParts = aspectRatio.split(':');
var ratioMultiplier = ratioParts[1] / ratioParts[0];
if (this.width_ !== undefined) {
// Use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// Or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratioMultiplier;
} else {
// Or use the video's metadata, or use the video el's default of 300
width = this.videoWidth() || 300;
}
if (this.height_ !== undefined) {
// Use any height that's been specifically set
height = this.height_;
} else {
// Otherwise calculate the height from the ratio and the width
height = width * ratioMultiplier;
}
// Ensure the CSS class is valid by starting with an alpha character
if (/^[^a-zA-Z]/.test(this.id())) {
idClass = 'dimensions-' + this.id();
} else {
idClass = this.id() + '-dimensions';
}
// Ensure the right class is still on the player for the style element
this.addClass(idClass);
stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n ');
};
/**
* Load the Media Playback Technology (tech)
* Load/Create an instance of playback technology including element and API methods
* And append playback element in player div.
*
* @param {String} techName Name of the playback technology
* @param {String} source Video source
* @method loadTech_
* @private
*/
Player.prototype.loadTech_ = function loadTech_(techName, source) {
// Pause and remove current playback technology
if (this.tech_) {
this.unloadTech_();
}
// get rid of the HTML5 video tag as soon as we are using another tech
if (techName !== 'Html5' && this.tag) {
_techTechJs2['default'].getTech('Html5').disposeMediaElement(this.tag);
this.tag.player = null;
this.tag = null;
}
this.techName_ = techName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = _objectAssign2['default']({
'nativeControlsForTouch': this.options_.nativeControlsForTouch,
'source': source,
'playerId': this.id(),
'techId': this.id() + '_' + techName + '_api',
'textTracks': this.textTracks_,
'autoplay': this.options_.autoplay,
'preload': this.options_.preload,
'loop': this.options_.loop,
'muted': this.options_.muted,
'poster': this.poster(),
'language': this.language(),
'vtt.js': this.options_['vtt.js']
}, this.options_[techName.toLowerCase()]);
if (this.tag) {
techOptions.tag = this.tag;
}
if (source) {
this.currentType_ = source.type;
if (source.src === this.cache_.src && this.cache_.currentTime > 0) {
techOptions.startTime = this.cache_.currentTime;
}
this.cache_.src = source.src;
}
// Initialize tech instance
var techComponent = _techTechJs2['default'].getTech(techName);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!techComponent) {
techComponent = _componentJs2['default'].getComponent(techName);
}
this.tech_ = new techComponent(techOptions);
// player.triggerReady is always async, so don't need this to be async
this.tech_.ready(Fn.bind(this, this.handleTechReady_), true);
_tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
// Listen to all HTML5-defined events and trigger them on the player
this.on(this.tech_, 'loadstart', this.handleTechLoadStart_);
this.on(this.tech_, 'waiting', this.handleTechWaiting_);
this.on(this.tech_, 'canplay', this.handleTechCanPlay_);
this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_);
this.on(this.tech_, 'playing', this.handleTechPlaying_);
this.on(this.tech_, 'ended', this.handleTechEnded_);
this.on(this.tech_, 'seeking', this.handleTechSeeking_);
this.on(this.tech_, 'seeked', this.handleTechSeeked_);
this.on(this.tech_, 'play', this.handleTechPlay_);
this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_);
this.on(this.tech_, 'pause', this.handleTechPause_);
this.on(this.tech_, 'progress', this.handleTechProgress_);
this.on(this.tech_, 'durationchange', this.handleTechDurationChange_);
this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_);
this.on(this.tech_, 'error', this.handleTechError_);
this.on(this.tech_, 'suspend', this.handleTechSuspend_);
this.on(this.tech_, 'abort', this.handleTechAbort_);
this.on(this.tech_, 'emptied', this.handleTechEmptied_);
this.on(this.tech_, 'stalled', this.handleTechStalled_);
this.on(this.tech_, 'loadedmetadata', this.handleTechLoadedMetaData_);
this.on(this.tech_, 'loadeddata', this.handleTechLoadedData_);
this.on(this.tech_, 'timeupdate', this.handleTechTimeUpdate_);
this.on(this.tech_, 'ratechange', this.handleTechRateChange_);
this.on(this.tech_, 'volumechange', this.handleTechVolumeChange_);
this.on(this.tech_, 'texttrackchange', this.handleTechTextTrackChange_);
this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_);
this.on(this.tech_, 'posterchange', this.handleTechPosterChange_);
this.usingNativeControls(this.techGet_('controls'));
if (this.controls() && !this.usingNativeControls()) {
this.addTechControlsListeners_();
}
// Add the tech element in the DOM if it was not already there
// Make sure to not insert the original video element if using Html5
if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) {
Dom.insertElFirst(this.tech_.el(), this.el());
}
// Get rid of the original video tag reference after the first tech is loaded
if (this.tag) {
this.tag.player = null;
this.tag = null;
}
};
/**
* Unload playback technology
*
* @method unloadTech_
* @private
*/
Player.prototype.unloadTech_ = function unloadTech_() {
// Save the current text tracks so that we can reuse the same text tracks with the next tech
this.textTracks_ = this.textTracks();
this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this.tech_);
this.isReady_ = false;
this.tech_.dispose();
this.tech_ = false;
};
/**
* Return a reference to the current tech.
* It will only return a reference to the tech if given an object with the
* `IWillNotUseThisInPlugins` property on it. This is try and prevent misuse
* of techs by plugins.
*
* @param {Object}
* @return {Object} The Tech
* @method tech
*/
Player.prototype.tech = function tech(safety) {
if (safety && safety.IWillNotUseThisInPlugins) {
return this.tech_;
}
var errorText = '\n Please make sure that you are not using this inside of a plugin.\n To disable this alert and error, please pass in an object with\n `IWillNotUseThisInPlugins` to the `tech` method. See\n https://github.com/videojs/video.js/issues/2617 for more info.\n ';
_globalWindow2['default'].alert(errorText);
throw new Error(errorText);
};
/**
* Set up click and touch listeners for the playback element
*
* On desktops, a click on the video itself will toggle playback,
* on a mobile device a click on the video toggles controls.
* (toggling controls is done by toggling the user state between active and
* inactive)
* A tap can signal that a user has become active, or has become inactive
* e.g. a quick tap on an iPhone movie should reveal the controls. Another
* quick tap should hide them again (signaling the user is in an inactive
* viewing state)
* In addition to this, we still want the user to be considered inactive after
* a few seconds of inactivity.
* Note: the only part of iOS interaction we can't mimic with this setup
* is a touch and hold on the video element counting as activity in order to
* keep the controls showing, but that shouldn't be an issue. A touch and hold
* on any controls will still keep the user active
*
* @private
* @method addTechControlsListeners_
*/
Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() {
// Make sure to remove all the previous listeners in case we are called multiple times.
this.removeTechControlsListeners_();
// Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
// trigger mousedown/up.
// http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
// Any touch events are set to block the mousedown event from happening
this.on(this.tech_, 'mousedown', this.handleTechClick_);
// If the controls were hidden we don't want that to change without a tap event
// so we'll check if the controls were already showing before reporting user
// activity
this.on(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.on(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.on(this.tech_, 'touchend', this.handleTechTouchEnd_);
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on(this.tech_, 'tap', this.handleTechTap_);
};
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*
* @method removeTechControlsListeners_
* @private
*/
Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() {
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off(this.tech_, 'tap', this.handleTechTap_);
this.off(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.off(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.off(this.tech_, 'touchend', this.handleTechTouchEnd_);
this.off(this.tech_, 'mousedown', this.handleTechClick_);
};
/**
* Player waits for the tech to be ready
*
* @method handleTechReady_
* @private
*/
Player.prototype.handleTechReady_ = function handleTechReady_() {
this.triggerReady();
// Keep the same volume as before
if (this.cache_.volume) {
this.techCall_('setVolume', this.cache_.volume);
}
// Look if the tech found a higher resolution poster while loading
this.handleTechPosterChange_();
// Update the duration if available
this.handleTechDurationChange_();
// Chrome and Safari both have issues with autoplay.
// In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work.
// In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays)
// This fixes both issues. Need to wait for API, so it updates displays correctly
if (this.tag && this.options_.autoplay && this.paused()) {
delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16.
this.play();
}
};
/**
* Fired when the user agent begins looking for media data
*
* @private
* @method handleTechLoadStart_
*/
Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() {
// TODO: Update to use `emptied` event instead. See #1277.
this.removeClass('vjs-ended');
// reset the error state
this.error(null);
// If it's already playing we want to trigger a firstplay event now.
// The firstplay event relies on both the play and loadstart events
// which can happen in any order for a new source
if (!this.paused()) {
this.trigger('loadstart');
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
this.trigger('loadstart');
}
};
/**
* Add/remove the vjs-has-started class
*
* @param {Boolean} hasStarted The value of true adds the class the value of false remove the class
* @return {Boolean} Boolean value if has started
* @private
* @method hasStarted
*/
Player.prototype.hasStarted = function hasStarted(_hasStarted) {
if (_hasStarted !== undefined) {
// only update if this is a new value
if (this.hasStarted_ !== _hasStarted) {
this.hasStarted_ = _hasStarted;
if (_hasStarted) {
this.addClass('vjs-has-started');
// trigger the firstplay event if this newly has played
this.trigger('firstplay');
} else {
this.removeClass('vjs-has-started');
}
}
return this;
}
return !!this.hasStarted_;
};
/**
* Fired whenever the media begins or resumes playback
*
* @private
* @method handleTechPlay_
*/
Player.prototype.handleTechPlay_ = function handleTechPlay_() {
this.removeClass('vjs-ended');
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
// hide the poster when the user hits play
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play
this.hasStarted(true);
this.trigger('play');
};
/**
* Fired whenever the media begins waiting
*
* @private
* @method handleTechWaiting_
*/
Player.prototype.handleTechWaiting_ = function handleTechWaiting_() {
this.addClass('vjs-waiting');
this.trigger('waiting');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlay_
*/
Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() {
this.removeClass('vjs-waiting');
this.trigger('canplay');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlayThrough_
*/
Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
this.removeClass('vjs-waiting');
this.trigger('canplaythrough');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechPlaying_
*/
Player.prototype.handleTechPlaying_ = function handleTechPlaying_() {
this.removeClass('vjs-waiting');
this.trigger('playing');
};
/**
* Fired whenever the player is jumping to a new time
*
* @private
* @method handleTechSeeking_
*/
Player.prototype.handleTechSeeking_ = function handleTechSeeking_() {
this.addClass('vjs-seeking');
this.trigger('seeking');
};
/**
* Fired when the player has finished jumping to a new time
*
* @private
* @method handleTechSeeked_
*/
Player.prototype.handleTechSeeked_ = function handleTechSeeked_() {
this.removeClass('vjs-seeking');
this.trigger('seeked');
};
/**
* Fired the first time a video is played
* Not part of the HLS spec, and we're not sure if this is the best
* implementation yet, so use sparingly. If you don't have a reason to
* prevent playback, use `myPlayer.one('play');` instead.
*
* @private
* @method handleTechFirstPlay_
*/
Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() {
//If the first starttime attribute is specified
//then we will start at the given offset in seconds
if (this.options_.starttime) {
this.currentTime(this.options_.starttime);
}
this.addClass('vjs-has-started');
this.trigger('firstplay');
};
/**
* Fired whenever the media has been paused
*
* @private
* @method handleTechPause_
*/
Player.prototype.handleTechPause_ = function handleTechPause_() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.trigger('pause');
};
/**
* Fired while the user agent is downloading media data
*
* @private
* @method handleTechProgress_
*/
Player.prototype.handleTechProgress_ = function handleTechProgress_() {
this.trigger('progress');
};
/**
* Fired when the end of the media resource is reached (currentTime == duration)
*
* @private
* @method handleTechEnded_
*/
Player.prototype.handleTechEnded_ = function handleTechEnded_() {
this.addClass('vjs-ended');
if (this.options_.loop) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
this.trigger('ended');
};
/**
* Fired when the duration of the media resource is first known or changed
*
* @private
* @method handleTechDurationChange_
*/
Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() {
this.duration(this.techGet_('duration'));
};
/**
* Handle a click on the media element to play/pause
*
* @param {Object=} event Event object
* @private
* @method handleTechClick_
*/
Player.prototype.handleTechClick_ = function handleTechClick_(event) {
// We're using mousedown to detect clicks thanks to Flash, but mousedown
// will also be triggered with right-clicks, so we need to prevent that
if (event.button !== 0) return;
// When controls are disabled a click should not toggle playback because
// the click is considered a control
if (this.controls()) {
if (this.paused()) {
this.play();
} else {
this.pause();
}
}
};
/**
* Handle a tap on the media element. It will toggle the user
* activity state, which hides and shows the controls.
*
* @private
* @method handleTechTap_
*/
Player.prototype.handleTechTap_ = function handleTechTap_() {
this.userActive(!this.userActive());
};
/**
* Handle touch to start
*
* @private
* @method handleTechTouchStart_
*/
Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() {
this.userWasActive = this.userActive();
};
/**
* Handle touch to move
*
* @private
* @method handleTechTouchMove_
*/
Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() {
if (this.userWasActive) {
this.reportUserActivity();
}
};
/**
* Handle touch to end
*
* @private
* @method handleTechTouchEnd_
*/
Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
// Stop the mouse events from also happening
event.preventDefault();
};
/**
* Fired when the player switches in or out of fullscreen mode
*
* @private
* @method handleFullscreenChange_
*/
Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
};
/**
* native click events on the SWF aren't triggered on IE11, Win8.1RT
* use stageclick events triggered from inside the SWF instead
*
* @private
* @method handleStageClick_
*/
Player.prototype.handleStageClick_ = function handleStageClick_() {
this.reportUserActivity();
};
/**
* Handle Tech Fullscreen Change
*
* @private
* @method handleTechFullscreenChange_
*/
Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
if (data) {
this.isFullscreen(data.isFullscreen);
}
this.trigger('fullscreenchange');
};
/**
* Fires when an error occurred during the loading of an audio/video
*
* @private
* @method handleTechError_
*/
Player.prototype.handleTechError_ = function handleTechError_() {
var error = this.tech_.error();
this.error(error && error.code);
};
/**
* Fires when the browser is intentionally not getting media data
*
* @private
* @method handleTechSuspend_
*/
Player.prototype.handleTechSuspend_ = function handleTechSuspend_() {
this.trigger('suspend');
};
/**
* Fires when the loading of an audio/video is aborted
*
* @private
* @method handleTechAbort_
*/
Player.prototype.handleTechAbort_ = function handleTechAbort_() {
this.trigger('abort');
};
/**
* Fires when the current playlist is empty
*
* @private
* @method handleTechEmptied_
*/
Player.prototype.handleTechEmptied_ = function handleTechEmptied_() {
this.trigger('emptied');
};
/**
* Fires when the browser is trying to get media data, but data is not available
*
* @private
* @method handleTechStalled_
*/
Player.prototype.handleTechStalled_ = function handleTechStalled_() {
this.trigger('stalled');
};
/**
* Fires when the browser has loaded meta data for the audio/video
*
* @private
* @method handleTechLoadedMetaData_
*/
Player.prototype.handleTechLoadedMetaData_ = function handleTechLoadedMetaData_() {
this.trigger('loadedmetadata');
};
/**
* Fires when the browser has loaded the current frame of the audio/video
*
* @private
* @method handleTechLoadedData_
*/
Player.prototype.handleTechLoadedData_ = function handleTechLoadedData_() {
this.trigger('loadeddata');
};
/**
* Fires when the current playback position has changed
*
* @private
* @method handleTechTimeUpdate_
*/
Player.prototype.handleTechTimeUpdate_ = function handleTechTimeUpdate_() {
this.trigger('timeupdate');
};
/**
* Fires when the playing speed of the audio/video is changed
*
* @private
* @method handleTechRateChange_
*/
Player.prototype.handleTechRateChange_ = function handleTechRateChange_() {
this.trigger('ratechange');
};
/**
* Fires when the volume has been changed
*
* @private
* @method handleTechVolumeChange_
*/
Player.prototype.handleTechVolumeChange_ = function handleTechVolumeChange_() {
this.trigger('volumechange');
};
/**
* Fires when the text track has been changed
*
* @private
* @method handleTechTextTrackChange_
*/
Player.prototype.handleTechTextTrackChange_ = function handleTechTextTrackChange_() {
this.trigger('texttrackchange');
};
/**
* Get object for cached values.
*
* @return {Object}
* @method getCache
*/
Player.prototype.getCache = function getCache() {
return this.cache_;
};
/**
* Pass values to the playback tech
*
* @param {String=} method Method
* @param {Object=} arg Argument
* @private
* @method techCall_
*/
Player.prototype.techCall_ = function techCall_(method, arg) {
// If it's not ready yet, call method when it is
if (this.tech_ && !this.tech_.isReady_) {
this.tech_.ready(function () {
this[method](arg);
}, true);
// Otherwise call method now
} else {
try {
this.tech_[method](arg);
} catch (e) {
_utilsLogJs2['default'](e);
throw e;
}
}
};
/**
* Get calls can't wait for the tech, and sometimes don't need to.
*
* @param {String} method Tech method
* @return {Method}
* @private
* @method techGet_
*/
Player.prototype.techGet_ = function techGet_(method) {
if (this.tech_ && this.tech_.isReady_) {
// Flash likes to die and reload when you hide or reposition it.
// In these cases the object methods go away and we get errors.
// When that happens we'll catch the errors and inform tech that it's not ready any more.
try {
return this.tech_[method]();
} catch (e) {
// When building additional tech libs, an expected method may not be defined yet
if (this.tech_[method] === undefined) {
_utilsLogJs2['default']('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e);
} else {
// When a method isn't available on the object it throws a TypeError
if (e.name === 'TypeError') {
_utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e);
this.tech_.isReady_ = false;
} else {
_utilsLogJs2['default'](e);
}
}
throw e;
}
}
return;
};
/**
* start media playback
* ```js
* myPlayer.play();
* ```
*
* @return {Player} self
* @method play
*/
Player.prototype.play = function play() {
this.techCall_('play');
return this;
};
/**
* Pause the video playback
* ```js
* myPlayer.pause();
* ```
*
* @return {Player} self
* @method pause
*/
Player.prototype.pause = function pause() {
this.techCall_('pause');
return this;
};
/**
* Check if the player is paused
* ```js
* var isPaused = myPlayer.paused();
* var isPlaying = !myPlayer.paused();
* ```
*
* @return {Boolean} false if the media is currently playing, or true otherwise
* @method paused
*/
Player.prototype.paused = function paused() {
// The initial state of paused should be true (in Safari it's actually false)
return this.techGet_('paused') === false ? false : true;
};
/**
* Returns whether or not the user is "scrubbing". Scrubbing is when the user
* has clicked the progress bar handle and is dragging it along the progress bar.
*
* @param {Boolean} isScrubbing True/false the user is scrubbing
* @return {Boolean} The scrubbing status when getting
* @return {Object} The player when setting
* @method scrubbing
*/
Player.prototype.scrubbing = function scrubbing(isScrubbing) {
if (isScrubbing !== undefined) {
this.scrubbing_ = !!isScrubbing;
if (isScrubbing) {
this.addClass('vjs-scrubbing');
} else {
this.removeClass('vjs-scrubbing');
}
return this;
}
return this.scrubbing_;
};
/**
* Get or set the current time (in seconds)
* ```js
* // get
* var whereYouAt = myPlayer.currentTime();
* // set
* myPlayer.currentTime(120); // 2 minutes into the video
* ```
*
* @param {Number|String=} seconds The time to seek to
* @return {Number} The time in seconds, when not setting
* @return {Player} self, when the current time is set
* @method currentTime
*/
Player.prototype.currentTime = function currentTime(seconds) {
if (seconds !== undefined) {
this.techCall_('setCurrentTime', seconds);
return this;
}
// cache last currentTime and return. default to 0 seconds
//
// Caching the currentTime is meant to prevent a massive amount of reads on the tech's
// currentTime when scrubbing, but may not provide much performance benefit afterall.
// Should be tested. Also something has to read the actual current time or the cache will
// never get updated.
return this.cache_.currentTime = this.techGet_('currentTime') || 0;
};
/**
* Get the length in time of the video in seconds
* ```js
* var lengthOfVideo = myPlayer.duration();
* ```
* **NOTE**: The video must have started loading before the duration can be
* known, and in the case of Flash, may not be known until the video starts
* playing.
*
* @param {Number} seconds Duration when setting
* @return {Number} The duration of the video in seconds when getting
* @method duration
*/
Player.prototype.duration = function duration(seconds) {
if (seconds === undefined) {
return this.cache_.duration || 0;
}
seconds = parseFloat(seconds) || 0;
// Standardize on Inifity for signaling video is live
if (seconds < 0) {
seconds = Infinity;
}
if (seconds !== this.cache_.duration) {
// Cache the last set value for optimized scrubbing (esp. Flash)
this.cache_.duration = seconds;
if (seconds === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
this.trigger('durationchange');
}
return this;
};
/**
* Calculates how much time is left.
* ```js
* var timeLeft = myPlayer.remainingTime();
* ```
* Not a native video element function, but useful
*
* @return {Number} The time remaining in seconds
* @method remainingTime
*/
Player.prototype.remainingTime = function remainingTime() {
return this.duration() - this.currentTime();
};
// http://dev.w3.org/html5/spec/video.html#dom-media-buffered
// Buffered returns a timerange object.
// Kind of like an array of portions of the video that have been downloaded.
/**
* Get a TimeRange object with the times of the video that have been downloaded
* If you just want the percent of the video that's been downloaded,
* use bufferedPercent.
* ```js
* // Number of different ranges of time have been buffered. Usually 1.
* numberOfRanges = bufferedTimeRange.length,
* // Time in seconds when the first range starts. Usually 0.
* firstRangeStart = bufferedTimeRange.start(0),
* // Time in seconds when the first range ends
* firstRangeEnd = bufferedTimeRange.end(0),
* // Length in seconds of the first time range
* firstRangeLength = firstRangeEnd - firstRangeStart;
* ```
*
* @return {Object} A mock TimeRange object (following HTML spec)
* @method buffered
*/
Player.prototype.buffered = function buffered() {
var buffered = this.techGet_('buffered');
if (!buffered || !buffered.length) {
buffered = _utilsTimeRangesJs.createTimeRange(0, 0);
}
return buffered;
};
/**
* Get the percent (as a decimal) of the video that's been downloaded
* ```js
* var howMuchIsDownloaded = myPlayer.bufferedPercent();
* ```
* 0 means none, 1 means all.
* (This method isn't in the HTML5 spec, but it's very convenient)
*
* @return {Number} A decimal between 0 and 1 representing the percent
* @method bufferedPercent
*/
Player.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration());
};
/**
* Get the ending time of the last buffered time range
* This is used in the progress bar to encapsulate all time ranges.
*
* @return {Number} The end of the last buffered time range
* @method bufferedEnd
*/
Player.prototype.bufferedEnd = function bufferedEnd() {
var buffered = this.buffered(),
duration = this.duration(),
end = buffered.end(buffered.length - 1);
if (end > duration) {
end = duration;
}
return end;
};
/**
* Get or set the current volume of the media
* ```js
* // get
* var howLoudIsIt = myPlayer.volume();
* // set
* myPlayer.volume(0.5); // Set volume to half
* ```
* 0 is off (muted), 1.0 is all the way up, 0.5 is half way.
*
* @param {Number} percentAsDecimal The new volume as a decimal percent
* @return {Number} The current volume when getting
* @return {Player} self when setting
* @method volume
*/
Player.prototype.volume = function volume(percentAsDecimal) {
var vol = undefined;
if (percentAsDecimal !== undefined) {
vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1
this.cache_.volume = vol;
this.techCall_('setVolume', vol);
return this;
}
// Default to 1 when returning current volume.
vol = parseFloat(this.techGet_('volume'));
return isNaN(vol) ? 1 : vol;
};
/**
* Get the current muted state, or turn mute on or off
* ```js
* // get
* var isVolumeMuted = myPlayer.muted();
* // set
* myPlayer.muted(true); // mute the volume
* ```
*
* @param {Boolean=} muted True to mute, false to unmute
* @return {Boolean} True if mute is on, false if not when getting
* @return {Player} self when setting mute
* @method muted
*/
Player.prototype.muted = function muted(_muted) {
if (_muted !== undefined) {
this.techCall_('setMuted', _muted);
return this;
}
return this.techGet_('muted') || false; // Default to false
};
// Check if current tech can support native fullscreen
// (e.g. with built in controls like iOS, so not our flash swf)
/**
* Check to see if fullscreen is supported
*
* @return {Boolean}
* @method supportsFullScreen
*/
Player.prototype.supportsFullScreen = function supportsFullScreen() {
return this.techGet_('supportsFullScreen') || false;
};
/**
* Check if the player is in fullscreen mode
* ```js
* // get
* var fullscreenOrNot = myPlayer.isFullscreen();
* // set
* myPlayer.isFullscreen(true); // tell the player it's in fullscreen
* ```
* NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
* property and instead document.fullscreenElement is used. But isFullscreen is
* still a valuable property for internal player workings.
*
* @param {Boolean=} isFS Update the player's fullscreen state
* @return {Boolean} true if fullscreen false if not when getting
* @return {Player} self when setting
* @method isFullscreen
*/
Player.prototype.isFullscreen = function isFullscreen(isFS) {
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return this;
}
return !!this.isFullscreen_;
};
/**
* Increase the size of the video to full screen
* ```js
* myPlayer.requestFullscreen();
* ```
* In some browsers, full screen is not supported natively, so it enters
* "full window mode", where the video fills the browser window.
* In browsers and devices that support native full screen, sometimes the
* browser's default controls will be shown, and not the Video.js custom skin.
* This includes most mobile devices (iOS, Android) and older versions of
* Safari.
*
* @return {Player} self
* @method requestFullscreen
*/
Player.prototype.requestFullscreen = function requestFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(true);
if (fsApi.requestFullscreen) {
// the browser supports going fullscreen at the element level so we can
// take the controls fullscreen as well as the video
// Trigger fullscreenchange event after change
// We have to specifically add this each time, and remove
// when canceling fullscreen. Otherwise if there's multiple
// players on a page, they would all be reacting to the same fullscreen
// events
Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) {
this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange);
}
this.trigger('fullscreenchange');
}));
this.el_[fsApi.requestFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
// we can't take the video.js controls fullscreen but we can go fullscreen
// with native controls
this.techCall_('enterFullScreen');
} else {
// fullscreen isn't supported so we'll just stretch the video element to
// fill the viewport
this.enterFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* Return the video to its normal size after having been in full screen mode
* ```js
* myPlayer.exitFullscreen();
* ```
*
* @return {Player} self
* @method exitFullscreen
*/
Player.prototype.exitFullscreen = function exitFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi.requestFullscreen) {
_globalDocument2['default'][fsApi.exitFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
this.techCall_('exitFullScreen');
} else {
this.exitFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
*
* @method enterFullWindow
*/
Player.prototype.enterFullWindow = function enterFullWindow() {
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
_globalDocument2['default'].documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window');
this.trigger('enterFullWindow');
};
/**
* Check for call to either exit full window or full screen on ESC key
*
* @param {String} event Event to check for key press
* @method fullWindowOnEscKey
*/
Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
};
/**
* Exit full window
*
* @method exitFullWindow
*/
Player.prototype.exitFullWindow = function exitFullWindow() {
this.isFullWindow = false;
Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
_globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
this.trigger('exitFullWindow');
};
/**
* Check whether the player can play a given mimetype
*
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
* @method canPlayType
*/
Player.prototype.canPlayType = function canPlayType(type) {
var can = undefined;
// Loop through each playback technology in the options order
for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
var techName = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _techTechJs2['default'].getTech(techName);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!tech) {
tech = _componentJs2['default'].getComponent(techName);
}
// Check if the current tech is defined before continuing
if (!tech) {
_utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
continue;
}
// Check if the browser supports this technology
if (tech.isSupported()) {
can = tech.canPlayType(type);
if (can) {
return can;
}
}
}
return '';
};
/**
* Select source based on tech-order or source-order
* Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
* defaults to tech-order selection
*
* @param {Array} sources The sources for a media asset
* @return {Object|Boolean} Object of source and tech order, otherwise false
* @method selectSource
*/
Player.prototype.selectSource = function selectSource(sources) {
// Get only the techs specified in `techOrder` that exist and are supported by the
// current platform
var techs = this.options_.techOrder.map(_utilsToTitleCaseJs2['default']).map(function (techName) {
// `Component.getComponent(...)` is for support of old behavior of techs
// being registered as components.
// Remove once that deprecated behavior is removed.
return [techName, _techTechJs2['default'].getTech(techName) || _componentJs2['default'].getComponent(techName)];
}).filter(function (_ref) {
var techName = _ref[0];
var tech = _ref[1];
// Check if the current tech is defined before continuing
if (tech) {
// Check if the browser supports this technology
return tech.isSupported();
}
_utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
return false;
});
// Iterate over each `innerArray` element once per `outerArray` element and execute
// `tester` with both. If `tester` returns a non-falsy value, exit early and return
// that value.
var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) {
var found = undefined;
outerArray.some(function (outerChoice) {
return innerArray.some(function (innerChoice) {
found = tester(outerChoice, innerChoice);
if (found) {
return true;
}
});
});
return found;
};
var foundSourceAndTech = undefined;
var flip = function flip(fn) {
return function (a, b) {
return fn(b, a);
};
};
var finder = function finder(_ref2, source) {
var techName = _ref2[0];
var tech = _ref2[1];
if (tech.canPlaySource(source)) {
return { source: source, tech: techName };
}
};
// Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
// to select from them based on their priority.
if (this.options_.sourceOrder) {
// Source-first ordering
foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
} else {
// Tech-first ordering
foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
}
return foundSourceAndTech || false;
};
/**
* The source function updates the video source
* There are three types of variables you can pass as the argument.
* **URL String**: A URL to the the video file. Use this method if you are sure
* the current playback technology (HTML5/Flash) can support the source you
* provide. Currently only MP4 files can be used in both HTML5 and Flash.
* ```js
* myPlayer.src("http://www.example.com/path/to/video.mp4");
* ```
* **Source Object (or element):* * A javascript object containing information
* about the source file. Use this method if you want the player to determine if
* it can support the file using the type information.
* ```js
* myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });
* ```
* **Array of Source Objects:* * To provide multiple versions of the source so
* that it can be played using HTML5 across browsers you can use an array of
* source objects. Video.js will detect which version is supported and load that
* file.
* ```js
* myPlayer.src([
* { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
* { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
* { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
* ]);
* ```
*
* @param {String|Object|Array=} source The source URL, object, or array of sources
* @return {String} The current video source when getting
* @return {String} The player when setting
* @method src
*/
Player.prototype.src = function src(source) {
if (source === undefined) {
return this.techGet_('src');
}
var currentTech = _techTechJs2['default'].getTech(this.techName_);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!currentTech) {
currentTech = _componentJs2['default'].getComponent(this.techName_);
}
// case: Array of source objects to choose from and pick the best to play
if (Array.isArray(source)) {
this.sourceList_(source);
// case: URL String (http://myvideo...)
} else if (typeof source === 'string') {
// create a source object from the string
this.src({ src: source });
// case: Source object { src: '', type: '' ... }
} else if (source instanceof Object) {
// check if the source has a type and the loaded tech cannot play the source
// if there's no type we'll just try the current tech
if (source.type && !currentTech.canPlaySource(source)) {
// create a source list with the current source and send through
// the tech loop to check for a compatible technology
this.sourceList_([source]);
} else {
this.cache_.src = source.src;
this.currentType_ = source.type || '';
// wait until the tech is ready to set the source
this.ready(function () {
// The setSource tech method was added with source handlers
// so older techs won't support it
// We need to check the direct prototype for the case where subclasses
// of the tech do not support source handlers
if (currentTech.prototype.hasOwnProperty('setSource')) {
this.techCall_('setSource', source);
} else {
this.techCall_('src', source.src);
}
if (this.options_.preload === 'auto') {
this.load();
}
if (this.options_.autoplay) {
this.play();
}
// Set the source synchronously if possible (#2326)
}, true);
}
}
return this;
};
/**
* Handle an array of source objects
*
* @param {Array} sources Array of source objects
* @private
* @method sourceList_
*/
Player.prototype.sourceList_ = function sourceList_(sources) {
var sourceTech = this.selectSource(sources);
if (sourceTech) {
if (sourceTech.tech === this.techName_) {
// if this technology is already loaded, set the source
this.src(sourceTech.source);
} else {
// load this technology with the chosen source
this.loadTech_(sourceTech.tech, sourceTech.source);
}
} else {
// We need to wrap this in a timeout to give folks a chance to add error event handlers
this.setTimeout(function () {
this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) });
}, 0);
// we could not find an appropriate tech, but let's still notify the delegate that this is it
// this needs a better comment about why this is needed
this.triggerReady();
}
};
/**
* Begin loading the src data.
*
* @return {Player} Returns the player
* @method load
*/
Player.prototype.load = function load() {
this.techCall_('load');
return this;
};
/**
* Reset the player. Loads the first tech in the techOrder,
* and calls `reset` on the tech`.
*
* @return {Player} Returns the player
* @method reset
*/
Player.prototype.reset = function reset() {
this.loadTech_(_utilsToTitleCaseJs2['default'](this.options_.techOrder[0]), null);
this.techCall_('reset');
return this;
};
/**
* Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
* Can be used in conjuction with `currentType` to assist in rebuilding the current source object.
*
* @return {String} The current source
* @method currentSrc
*/
Player.prototype.currentSrc = function currentSrc() {
return this.techGet_('currentSrc') || this.cache_.src || '';
};
/**
* Get the current source type e.g. video/mp4
* This can allow you rebuild the current source object so that you could load the same
* source and tech later
*
* @return {String} The source MIME type
* @method currentType
*/
Player.prototype.currentType = function currentType() {
return this.currentType_ || '';
};
/**
* Get or set the preload attribute
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The preload attribute value when getting
* @return {Player} Returns the player when setting
* @method preload
*/
Player.prototype.preload = function preload(value) {
if (value !== undefined) {
this.techCall_('setPreload', value);
this.options_.preload = value;
return this;
}
return this.techGet_('preload');
};
/**
* Get or set the autoplay attribute.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The autoplay attribute value when getting
* @return {Player} Returns the player when setting
* @method autoplay
*/
Player.prototype.autoplay = function autoplay(value) {
if (value !== undefined) {
this.techCall_('setAutoplay', value);
this.options_.autoplay = value;
return this;
}
return this.techGet_('autoplay', value);
};
/**
* Get or set the loop attribute on the video element.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The loop attribute value when getting
* @return {Player} Returns the player when setting
* @method loop
*/
Player.prototype.loop = function loop(value) {
if (value !== undefined) {
this.techCall_('setLoop', value);
this.options_['loop'] = value;
return this;
}
return this.techGet_('loop');
};
/**
* Get or set the poster image source url
*
* ##### EXAMPLE:
* ```js
* // get
* var currentPoster = myPlayer.poster();
* // set
* myPlayer.poster('http://example.com/myImage.jpg');
* ```
*
* @param {String=} src Poster image source URL
* @return {String} poster URL when getting
* @return {Player} self when setting
* @method poster
*/
Player.prototype.poster = function poster(src) {
if (src === undefined) {
return this.poster_;
}
// The correct way to remove a poster is to set as an empty string
// other falsey values will throw errors
if (!src) {
src = '';
}
// update the internal poster variable
this.poster_ = src;
// update the tech's poster
this.techCall_('setPoster', src);
// alert components that the poster has been set
this.trigger('posterchange');
return this;
};
/**
* Some techs (e.g. YouTube) can provide a poster source in an
* asynchronous way. We want the poster component to use this
* poster source so that it covers up the tech's controls.
* (YouTube's play button). However we only want to use this
* soruce if the player user hasn't set a poster through
* the normal APIs.
*
* @private
* @method handleTechPosterChange_
*/
Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() {
if (!this.poster_ && this.tech_ && this.tech_.poster) {
this.poster_ = this.tech_.poster() || '';
// Let components know the poster has changed
this.trigger('posterchange');
}
};
/**
* Get or set whether or not the controls are showing.
*
* @param {Boolean} bool Set controls to showing or not
* @return {Boolean} Controls are showing
* @method controls
*/
Player.prototype.controls = function controls(bool) {
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.controls_ !== bool) {
this.controls_ = bool;
if (this.usingNativeControls()) {
this.techCall_('setControls', bool);
}
if (bool) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
this.trigger('controlsenabled');
if (!this.usingNativeControls()) {
this.addTechControlsListeners_();
}
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
this.trigger('controlsdisabled');
if (!this.usingNativeControls()) {
this.removeTechControlsListeners_();
}
}
}
return this;
}
return !!this.controls_;
};
/**
* Toggle native controls on/off. Native controls are the controls built into
* devices (e.g. default iPhone controls), Flash, or other techs
* (e.g. Vimeo Controls)
* **This should only be set by the current tech, because only the tech knows
* if it can support native controls**
*
* @param {Boolean} bool True signals that native controls are on
* @return {Player} Returns the player
* @private
* @method usingNativeControls
*/
Player.prototype.usingNativeControls = function usingNativeControls(bool) {
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.usingNativeControls_ !== bool) {
this.usingNativeControls_ = bool;
if (bool) {
this.addClass('vjs-using-native-controls');
/**
* player is using the native device controls
*
* @event usingnativecontrols
* @memberof Player
* @instance
* @private
*/
this.trigger('usingnativecontrols');
} else {
this.removeClass('vjs-using-native-controls');
/**
* player is using the custom HTML controls
*
* @event usingcustomcontrols
* @memberof Player
* @instance
* @private
*/
this.trigger('usingcustomcontrols');
}
}
return this;
}
return !!this.usingNativeControls_;
};
/**
* Set or get the current MediaError
*
* @param {*} err A MediaError or a String/Number to be turned into a MediaError
* @return {MediaError|null} when getting
* @return {Player} when setting
* @method error
*/
Player.prototype.error = function error(err) {
if (err === undefined) {
return this.error_ || null;
}
// restoring to default
if (err === null) {
this.error_ = err;
this.removeClass('vjs-error');
this.errorDisplay.close();
return this;
}
// error instance
if (err instanceof _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['default'](err);
}
// add the vjs-error classname to the player
this.addClass('vjs-error');
// log the name of the error type and any message
// ie8 just logs "[object object]" if you just log the error object
_utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
// fire an error event on the player
this.trigger('error');
return this;
};
/**
* Returns whether or not the player is in the "ended" state.
*
* @return {Boolean} True if the player is in the ended state, false if not.
* @method ended
*/
Player.prototype.ended = function ended() {
return this.techGet_('ended');
};
/**
* Returns whether or not the player is in the "seeking" state.
*
* @return {Boolean} True if the player is in the seeking state, false if not.
* @method seeking
*/
Player.prototype.seeking = function seeking() {
return this.techGet_('seeking');
};
/**
* Returns the TimeRanges of the media that are currently available
* for seeking to.
*
* @return {TimeRanges} the seekable intervals of the media timeline
* @method seekable
*/
Player.prototype.seekable = function seekable() {
return this.techGet_('seekable');
};
/**
* Report user activity
*
* @param {Object} event Event object
* @method reportUserActivity
*/
Player.prototype.reportUserActivity = function reportUserActivity(event) {
this.userActivity_ = true;
};
/**
* Get/set if user is active
*
* @param {Boolean} bool Value when setting
* @return {Boolean} Value if user is active user when getting
* @method userActive
*/
Player.prototype.userActive = function userActive(bool) {
if (bool !== undefined) {
bool = !!bool;
if (bool !== this.userActive_) {
this.userActive_ = bool;
if (bool) {
// If the user was inactive and is now active we want to reset the
// inactivity timer
this.userActivity_ = true;
this.removeClass('vjs-user-inactive');
this.addClass('vjs-user-active');
this.trigger('useractive');
} else {
// We're switching the state to inactive manually, so erase any other
// activity
this.userActivity_ = false;
// Chrome/Safari/IE have bugs where when you change the cursor it can
// trigger a mousemove event. This causes an issue when you're hiding
// the cursor when the user is inactive, and a mousemove signals user
// activity. Making it impossible to go into inactive mode. Specifically
// this happens in fullscreen when we really need to hide the cursor.
//
// When this gets resolved in ALL browsers it can be removed
// https://code.google.com/p/chromium/issues/detail?id=103041
if (this.tech_) {
this.tech_.one('mousemove', function (e) {
e.stopPropagation();
e.preventDefault();
});
}
this.removeClass('vjs-user-active');
this.addClass('vjs-user-inactive');
this.trigger('userinactive');
}
}
return this;
}
return this.userActive_;
};
/**
* Listen for user activity based on timeout value
*
* @private
* @method listenForUserActivity_
*/
Player.prototype.listenForUserActivity_ = function listenForUserActivity_() {
var mouseInProgress = undefined,
lastMoveX = undefined,
lastMoveY = undefined;
var handleActivity = Fn.bind(this, this.reportUserActivity);
var handleMouseMove = function handleMouseMove(e) {
// #1068 - Prevent mousemove spamming
// Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
lastMoveX = e.screenX;
lastMoveY = e.screenY;
handleActivity();
}
};
var handleMouseDown = function handleMouseDown() {
handleActivity();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(mouseInProgress);
// Setting userActivity=true now and setting the interval to the same time
// as the activityCheck interval (250) should ensure we never miss the
// next activityCheck
mouseInProgress = this.setInterval(handleActivity, 250);
};
var handleMouseUp = function handleMouseUp(event) {
handleActivity();
// Stop the interval that maintains activity if the mouse/touch is down
this.clearInterval(mouseInProgress);
};
// Any mouse movement will be considered user activity
this.on('mousedown', handleMouseDown);
this.on('mousemove', handleMouseMove);
this.on('mouseup', handleMouseUp);
// Listen for keyboard navigation
// Shouldn't need to use inProgress interval because of key repeat
this.on('keydown', handleActivity);
this.on('keyup', handleActivity);
// Run an interval every 250 milliseconds instead of stuffing everything into
// the mousemove/touchmove function itself, to prevent performance degradation.
// `this.reportUserActivity` simply sets this.userActivity_ to true, which
// then gets picked up by this loop
// http://ejohn.org/blog/learning-from-twitter/
var inactivityTimeout = undefined;
var activityCheck = this.setInterval(function () {
// Check to see if mouse/touch activity has happened
if (this.userActivity_) {
// Reset the activity tracker
this.userActivity_ = false;
// If the user state was inactive, set the state to active
this.userActive(true);
// Clear any existing inactivity timeout to start the timer over
this.clearTimeout(inactivityTimeout);
var timeout = this.options_['inactivityTimeout'];
if (timeout > 0) {
// In <timeout> milliseconds, if no more activity has occurred the
// user will be considered inactive
inactivityTimeout = this.setTimeout(function () {
// Protect against the case where the inactivityTimeout can trigger just
// before the next user activity is picked up by the activityCheck loop
// causing a flicker
if (!this.userActivity_) {
this.userActive(false);
}
}, timeout);
}
}
}, 250);
};
/**
* Gets or sets the current playback rate. A playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed
* playback, for instance.
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*
* @param {Number} rate New playback rate to set.
* @return {Number} Returns the new playback rate when setting
* @return {Number} Returns the current playback rate when getting
* @method playbackRate
*/
Player.prototype.playbackRate = function playbackRate(rate) {
if (rate !== undefined) {
this.techCall_('setPlaybackRate', rate);
return this;
}
if (this.tech_ && this.tech_['featuresPlaybackRate']) {
return this.techGet_('playbackRate');
} else {
return 1.0;
}
};
/**
* Gets or sets the audio flag
*
* @param {Boolean} bool True signals that this is an audio player.
* @return {Boolean} Returns true if player is audio, false if not when getting
* @return {Player} Returns the player if setting
* @private
* @method isAudio
*/
Player.prototype.isAudio = function isAudio(bool) {
if (bool !== undefined) {
this.isAudio_ = !!bool;
return this;
}
return !!this.isAudio_;
};
/**
* Returns the current state of network activity for the element, from
* the codes in the list below.
* - NETWORK_EMPTY (numeric value 0)
* The element has not yet been initialised. All attributes are in
* their initial states.
* - NETWORK_IDLE (numeric value 1)
* The element's resource selection algorithm is active and has
* selected a resource, but it is not actually using the network at
* this time.
* - NETWORK_LOADING (numeric value 2)
* The user agent is actively trying to download data.
* - NETWORK_NO_SOURCE (numeric value 3)
* The element's resource selection algorithm is active, but it has
* not yet found a resource to use.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
* @return {Number} the current network activity state
* @method networkState
*/
Player.prototype.networkState = function networkState() {
return this.techGet_('networkState');
};
/**
* Returns a value that expresses the current state of the element
* with respect to rendering the current playback position, from the
* codes in the list below.
* - HAVE_NOTHING (numeric value 0)
* No information regarding the media resource is available.
* - HAVE_METADATA (numeric value 1)
* Enough of the resource has been obtained that the duration of the
* resource is available.
* - HAVE_CURRENT_DATA (numeric value 2)
* Data for the immediate current playback position is available.
* - HAVE_FUTURE_DATA (numeric value 3)
* Data for the immediate current playback position is available, as
* well as enough data for the user agent to advance the current
* playback position in the direction of playback.
* - HAVE_ENOUGH_DATA (numeric value 4)
* The user agent estimates that enough data is available for
* playback to proceed uninterrupted.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
* @return {Number} the current playback rendering state
* @method readyState
*/
Player.prototype.readyState = function readyState() {
return this.techGet_('readyState');
};
/*
* Text tracks are tracks of timed text events.
* Captions - text displayed over the video for the hearing impaired
* Subtitles - text displayed over the video for those who don't understand language in the video
* Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video
* Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device
*/
/**
* Get an array of associated text tracks. captions, subtitles, chapters, descriptions
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
*
* @return {Array} Array of track objects
* @method textTracks
*/
Player.prototype.textTracks = function textTracks() {
// cannot use techGet_ directly because it checks to see whether the tech is ready.
// Flash is unlikely to be ready in time but textTracks should still work.
return this.tech_ && this.tech_['textTracks']();
};
/**
* Get an array of remote text tracks
*
* @return {Array}
* @method remoteTextTracks
*/
Player.prototype.remoteTextTracks = function remoteTextTracks() {
return this.tech_ && this.tech_['remoteTextTracks']();
};
/**
* Get an array of remote html track elements
*
* @return {HTMLTrackElement[]}
* @method remoteTextTrackEls
*/
Player.prototype.remoteTextTrackEls = function remoteTextTrackEls() {
return this.tech_ && this.tech_['remoteTextTrackEls']();
};
/**
* Add a text track
* In addition to the W3C settings we allow adding additional info through options.
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
*
* @param {String} kind Captions, subtitles, chapters, descriptions, or metadata
* @param {String=} label Optional label
* @param {String=} language Optional language
* @method addTextTrack
*/
Player.prototype.addTextTrack = function addTextTrack(kind, label, language) {
return this.tech_ && this.tech_['addTextTrack'](kind, label, language);
};
/**
* Add a remote text track
*
* @param {Object} options Options for remote text track
* @method addRemoteTextTrack
*/
Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
return this.tech_ && this.tech_['addRemoteTextTrack'](options);
};
/**
* Remove a remote text track
*
* @param {Object} track Remote text track to remove
* @method removeRemoteTextTrack
*/
Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.tech_ && this.tech_['removeRemoteTextTrack'](track);
};
/**
* Get video width
*
* @return {Number} Video width
* @method videoWidth
*/
Player.prototype.videoWidth = function videoWidth() {
return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
};
/**
* Get video height
*
* @return {Number} Video height
* @method videoHeight
*/
Player.prototype.videoHeight = function videoHeight() {
return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
};
// Methods to add support for
// initialTime: function(){ return this.techCall_('initialTime'); },
// startOffsetTime: function(){ return this.techCall_('startOffsetTime'); },
// played: function(){ return this.techCall_('played'); },
// videoTracks: function(){ return this.techCall_('videoTracks'); },
// audioTracks: function(){ return this.techCall_('audioTracks'); },
// defaultPlaybackRate: function(){ return this.techCall_('defaultPlaybackRate'); },
// defaultMuted: function(){ return this.techCall_('defaultMuted'); }
/**
* The player's language code
* NOTE: The language should be set in the player options if you want the
* the controls to be built with a specific language. Changing the lanugage
* later will not update controls text.
*
* @param {String} code The locale string
* @return {String} The locale string when getting
* @return {Player} self when setting
* @method language
*/
Player.prototype.language = function language(code) {
if (code === undefined) {
return this.language_;
}
this.language_ = ('' + code).toLowerCase();
return this;
};
/**
* Get the player's language dictionary
* Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
* Languages specified directly in the player options have precedence
*
* @return {Array} Array of languages
* @method languages
*/
Player.prototype.languages = function languages() {
return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_);
};
/**
* Converts track info to JSON
*
* @return {Object} JSON object of options
* @method toJSON
*/
Player.prototype.toJSON = function toJSON() {
var options = _utilsMergeOptionsJs2['default'](this.options_);
var tracks = options.tracks;
options.tracks = [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// deep merge tracks and null out player so no circular references
track = _utilsMergeOptionsJs2['default'](track);
track.player = undefined;
options.tracks[i] = track;
}
return options;
};
/**
* Creates a simple modal dialog (an instance of the `ModalDialog`
* component) that immediately overlays the player with arbitrary
* content and removes itself when closed.
*
* @param {String|Function|Element|Array|Null} content
* Same as `ModalDialog#content`'s param of the same name.
*
* The most straight-forward usage is to provide a string or DOM
* element.
*
* @param {Object} [options]
* Extra options which will be passed on to the `ModalDialog`.
*
* @return {ModalDialog}
*/
Player.prototype.createModal = function createModal(content, options) {
var player = this;
options = options || {};
options.content = content || '';
var modal = new _modalDialog2['default'](player, options);
player.addChild(modal);
modal.on('dispose', function () {
player.removeChild(modal);
});
return modal.open();
};
/**
* Gets tag settings
*
* @param {Element} tag The player tag
* @return {Array} An array of sources and track objects
* @static
* @method getTagSettings
*/
Player.getTagSettings = function getTagSettings(tag) {
var baseOptions = {
'sources': [],
'tracks': []
};
var tagOptions = Dom.getElAttributes(tag);
var dataSetup = tagOptions['data-setup'];
// Check if data-setup attr exists.
if (dataSetup !== null) {
// Parse options JSON
var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}');
var err = _safeParseTuple[0];
var data = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
_objectAssign2['default'](tagOptions, data);
}
_objectAssign2['default'](baseOptions, tagOptions);
// Get tag children settings
if (tag.hasChildNodes()) {
var children = tag.childNodes;
for (var i = 0, j = children.length; i < j; i++) {
var child = children[i];
// Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
var childName = child.nodeName.toLowerCase();
if (childName === 'source') {
baseOptions.sources.push(Dom.getElAttributes(child));
} else if (childName === 'track') {
baseOptions.tracks.push(Dom.getElAttributes(child));
}
}
}
return baseOptions;
};
return Player;
})(_componentJs2['default']);
Player.players = {};
var navigator = _globalWindow2['default'].navigator;
/*
* Player instance options, surfaced using options
* options = Player.prototype.options_
* Make changes in options, not here.
*
* @type {Object}
* @private
*/
Player.prototype.options_ = {
// Default order of fallback technology
techOrder: ['html5', 'flash'],
// techOrder: ['flash','html5'],
html5: {},
flash: {},
// defaultVolume: 0.85,
defaultVolume: 0.00, // The freakin seaguls are driving me crazy!
// default inactivity timeout
inactivityTimeout: 2000,
// default playback rates
playbackRates: [],
// Add playback rate selection by adding rates
// 'playbackRates': [0.5, 1, 1.5, 2],
// Included control sets
children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'],
language: _globalDocument2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en',
// locales and their language translations
languages: {},
// Default message to show when a video cannot be played.
notSupportedMessage: 'No compatible source was found for this video.'
};
/**
* Fired when the player has initial duration and dimension information
*
* @event loadedmetadata
*/
Player.prototype.handleLoadedMetaData_;
/**
* Fired when the player has downloaded data at the current playback position
*
* @event loadeddata
*/
Player.prototype.handleLoadedData_;
/**
* Fired when the user is active, e.g. moves the mouse over the player
*
* @event useractive
*/
Player.prototype.handleUserActive_;
/**
* Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction
*
* @event userinactive
*/
Player.prototype.handleUserInactive_;
/**
* Fired when the current playback position has changed *
* During playback this is fired every 15-250 milliseconds, depending on the
* playback technology in use.
*
* @event timeupdate
*/
Player.prototype.handleTimeUpdate_;
/**
* Fired when video playback ends
*
* @event ended
*/
Player.prototype.handleTechEnded_;
/**
* Fired when the volume changes
*
* @event volumechange
*/
Player.prototype.handleVolumeChange_;
/**
* Fired when an error occurs
*
* @event error
*/
Player.prototype.handleError_;
Player.prototype.flexNotSupported_ = function () {
var elem = _globalDocument2['default'].createElement('i');
// Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
// common flex features that we can rely on when checking for flex support.
return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */;
};
_componentJs2['default'].registerComponent('Player', Player);
exports['default'] = Player;
module.exports = exports['default'];
// If empty string, make it a parsable json object.
},{"./big-play-button.js":62,"./component.js":65,"./control-bar/control-bar.js":66,"./error-display.js":96,"./fullscreen-api.js":99,"./loading-spinner.js":100,"./media-error.js":101,"./modal-dialog":105,"./poster-image.js":108,"./tech/html5.js":113,"./tech/loader.js":114,"./tech/tech.js":115,"./tracks/text-track-display.js":119,"./tracks/text-track-list-converter.js":121,"./tracks/text-track-settings.js":123,"./utils/browser.js":125,"./utils/buffer.js":126,"./utils/dom.js":128,"./utils/events.js":129,"./utils/fn.js":130,"./utils/guid.js":132,"./utils/log.js":133,"./utils/merge-options.js":134,"./utils/stylesheet.js":135,"./utils/time-ranges.js":136,"./utils/to-title-case.js":137,"global/document":1,"global/window":2,"object.assign":45,"safe-json-parse/tuple":53}],107:[function(_dereq_,module,exports){
/**
* @file plugins.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _playerJs = _dereq_('./player.js');
var _playerJs2 = _interopRequireDefault(_playerJs);
/**
* The method for registering a video.js plugin
*
* @param {String} name The name of the plugin
* @param {Function} init The function that is run when the player inits
* @method plugin
*/
var plugin = function plugin(name, init) {
_playerJs2['default'].prototype[name] = init;
};
exports['default'] = plugin;
module.exports = exports['default'];
},{"./player.js":106}],108:[function(_dereq_,module,exports){
/**
* @file poster-image.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
/**
* The component that handles showing the poster image.
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PosterImage
*/
var PosterImage = (function (_Button) {
_inherits(PosterImage, _Button);
function PosterImage(player, options) {
_classCallCheck(this, PosterImage);
_Button.call(this, player, options);
this.update();
player.on('posterchange', Fn.bind(this, this.update));
}
/**
* Clean up the poster image
*
* @method dispose
*/
PosterImage.prototype.dispose = function dispose() {
this.player().off('posterchange', this.update);
_Button.prototype.dispose.call(this);
};
/**
* Create the poster's image element
*
* @return {Element}
* @method createEl
*/
PosterImage.prototype.createEl = function createEl() {
var el = Dom.createEl('div', {
className: 'vjs-poster',
// Don't want poster to be tabbable.
tabIndex: -1
});
// To ensure the poster image resizes while maintaining its original aspect
// ratio, use a div with `background-size` when available. For browsers that
// do not support `background-size` (e.g. IE8), fall back on using a regular
// img element.
if (!browser.BACKGROUND_SIZE_SUPPORTED) {
this.fallbackImg_ = Dom.createEl('img');
el.appendChild(this.fallbackImg_);
}
return el;
};
/**
* Event handler for updates to the player's poster source
*
* @method update
*/
PosterImage.prototype.update = function update() {
var url = this.player().poster();
this.setSrc(url);
// If there's no poster source we should display:none on this component
// so it's not still clickable or right-clickable
if (url) {
this.show();
} else {
this.hide();
}
};
/**
* Set the poster source depending on the display method
*
* @param {String} url The URL to the poster source
* @method setSrc
*/
PosterImage.prototype.setSrc = function setSrc(url) {
if (this.fallbackImg_) {
this.fallbackImg_.src = url;
} else {
var backgroundImage = '';
// Any falsey values should stay as an empty string, otherwise
// this will throw an extra error
if (url) {
backgroundImage = 'url("' + url + '")';
}
this.el_.style.backgroundImage = backgroundImage;
}
};
/**
* Event handler for clicks on the poster image
*
* @method handleClick
*/
PosterImage.prototype.handleClick = function handleClick() {
// We don't want a click to trigger playback when controls are disabled
// but CSS should be hiding the poster to prevent that from happening
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
return PosterImage;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('PosterImage', PosterImage);
exports['default'] = PosterImage;
module.exports = exports['default'];
},{"./button.js":63,"./component.js":65,"./utils/browser.js":125,"./utils/dom.js":128,"./utils/fn.js":130}],109:[function(_dereq_,module,exports){
/**
* @file setup.js
*
* Functions for automatically setting up a player
* based on the data-setup attribute of the video tag
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _windowLoaded = false;
var videojs = undefined;
// Automatically set up any tags that have a data-setup attribute
var autoSetup = function autoSetup() {
// One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack*
// var vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
// var audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
// var mediaEls = vids.concat(audios);
// Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements
// to build up a new, combined list of elements.
var vids = _globalDocument2['default'].getElementsByTagName('video');
var audios = _globalDocument2['default'].getElementsByTagName('audio');
var mediaEls = [];
if (vids && vids.length > 0) {
for (var i = 0, e = vids.length; i < e; i++) {
mediaEls.push(vids[i]);
}
}
if (audios && audios.length > 0) {
for (var i = 0, e = audios.length; i < e; i++) {
mediaEls.push(audios[i]);
}
}
// Check if any media elements exist
if (mediaEls && mediaEls.length > 0) {
for (var i = 0, e = mediaEls.length; i < e; i++) {
var mediaEl = mediaEls[i];
// Check if element exists, has getAttribute func.
// IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately.
if (mediaEl && mediaEl.getAttribute) {
// Make sure this player hasn't already been set up.
if (mediaEl['player'] === undefined) {
var options = mediaEl.getAttribute('data-setup');
// Check if data-setup attr exists.
// We only auto-setup if they've added the data-setup attr.
if (options !== null) {
// Create new video.js instance.
var player = videojs(mediaEl);
}
}
// If getAttribute isn't defined, we need to wait for the DOM.
} else {
autoSetupTimeout(1);
break;
}
}
// No videos were found, so keep looping unless page is finished loading.
} else if (!_windowLoaded) {
autoSetupTimeout(1);
}
};
// Pause to let the DOM keep processing
var autoSetupTimeout = function autoSetupTimeout(wait, vjs) {
videojs = vjs;
setTimeout(autoSetup, wait);
};
if (_globalDocument2['default'].readyState === 'complete') {
_windowLoaded = true;
} else {
Events.one(_globalWindow2['default'], 'load', function () {
_windowLoaded = true;
});
}
var hasLoaded = function hasLoaded() {
return _windowLoaded;
};
exports.autoSetup = autoSetup;
exports.autoSetupTimeout = autoSetupTimeout;
exports.hasLoaded = hasLoaded;
},{"./utils/events.js":129,"global/document":1,"global/window":2}],110:[function(_dereq_,module,exports){
/**
* @file slider.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The base functionality for sliders like the volume bar and seek bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class Slider
*/
var Slider = (function (_Component) {
_inherits(Slider, _Component);
function Slider(player, options) {
_classCallCheck(this, Slider);
_Component.call(this, player, options);
// Set property names to bar to match with the child Slider class is looking for
this.bar = this.getChild(this.options_.barName);
// Set a horizontal or vertical class on the slider depending on the slider type
this.vertical(!!this.options_.vertical);
this.on('mousedown', this.handleMouseDown);
this.on('touchstart', this.handleMouseDown);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
this.on('click', this.handleClick);
this.on(player, 'controlsvisible', this.update);
this.on(player, this.playerEvent, this.update);
}
/**
* Create the component's DOM element
*
* @param {String} type Type of element to create
* @param {Object=} props List of properties in Object form
* @return {Element}
* @method createEl
*/
Slider.prototype.createEl = function createEl(type) {
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = _objectAssign2['default']({
tabIndex: 0
}, props);
attributes = _objectAssign2['default']({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
tabIndex: 0
}, attributes);
return _Component.prototype.createEl.call(this, type, props, attributes);
};
/**
* Handle mouse down on slider
*
* @param {Object} event Mouse down event object
* @method handleMouseDown
*/
Slider.prototype.handleMouseDown = function handleMouseDown(event) {
event.preventDefault();
Dom.blockTextSelection();
this.addClass('vjs-sliding');
this.trigger('slideractive');
this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.handleMouseMove(event);
};
/**
* To be overridden by a subclass
*
* @method handleMouseMove
*/
Slider.prototype.handleMouseMove = function handleMouseMove() {};
/**
* Handle mouse up on Slider
*
* @method handleMouseUp
*/
Slider.prototype.handleMouseUp = function handleMouseUp() {
Dom.unblockTextSelection();
this.removeClass('vjs-sliding');
this.trigger('sliderinactive');
this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.update();
};
/**
* Update slider
*
* @method update
*/
Slider.prototype.update = function update() {
// In VolumeBar init we have a setTimeout for update that pops and update to the end of the
// execution stack. The player is destroyed before then update will cause an error
if (!this.el_) return;
// If scrubbing, we could use a cached value to make the handle keep up with the user's mouse.
// On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later.
// var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration();
var progress = this.getPercent();
var bar = this.bar;
// If there's no bar...
if (!bar) return;
// Protect against no duration and other division issues
if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) {
progress = 0;
}
// Convert to a percentage for setting
var percentage = (progress * 100).toFixed(2) + '%';
// Set the new bar width or height
if (this.vertical()) {
bar.el().style.height = percentage;
} else {
bar.el().style.width = percentage;
}
};
/**
* Calculate distance for slider
*
* @param {Object} event Event object
* @method calculateDistance
*/
Slider.prototype.calculateDistance = function calculateDistance(event) {
var position = Dom.getPointerPosition(this.el_, event);
if (this.vertical()) {
return position.y;
}
return position.x;
};
/**
* Handle on focus for slider
*
* @method handleFocus
*/
Slider.prototype.handleFocus = function handleFocus() {
this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Handle key press for slider
*
* @param {Object} event Event object
* @method handleKeyPress
*/
Slider.prototype.handleKeyPress = function handleKeyPress(event) {
if (event.which === 37 || event.which === 40) {
// Left and Down Arrows
event.preventDefault();
this.stepBack();
} else if (event.which === 38 || event.which === 39) {
// Up and Right Arrows
event.preventDefault();
this.stepForward();
}
};
/**
* Handle on blur for slider
*
* @method handleBlur
*/
Slider.prototype.handleBlur = function handleBlur() {
this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
*
* @param {Object} event Event object
* @method handleClick
*/
Slider.prototype.handleClick = function handleClick(event) {
event.stopImmediatePropagation();
event.preventDefault();
};
/**
* Get/set if slider is horizontal for vertical
*
* @param {Boolean} bool True if slider is vertical, false is horizontal
* @return {Boolean} True if slider is vertical, false is horizontal
* @method vertical
*/
Slider.prototype.vertical = function vertical(bool) {
if (bool === undefined) {
return this.vertical_ || false;
}
this.vertical_ = !!bool;
if (this.vertical_) {
this.addClass('vjs-slider-vertical');
} else {
this.addClass('vjs-slider-horizontal');
}
return this;
};
return Slider;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Slider', Slider);
exports['default'] = Slider;
module.exports = exports['default'];
},{"../component.js":65,"../utils/dom.js":128,"global/document":1,"object.assign":45}],111:[function(_dereq_,module,exports){
/**
* @file flash-rtmp.js
*/
'use strict';
exports.__esModule = true;
function FlashRtmpDecorator(Flash) {
Flash.streamingFormats = {
'rtmp/mp4': 'MP4',
'rtmp/flv': 'FLV'
};
Flash.streamFromParts = function (connection, stream) {
return connection + '&' + stream;
};
Flash.streamToParts = function (src) {
var parts = {
connection: '',
stream: ''
};
if (!src) return parts;
// Look for the normal URL separator we expect, '&'.
// If found, we split the URL into two pieces around the
// first '&'.
var connEnd = src.search(/&(?!\w+=)/);
var streamBegin = undefined;
if (connEnd !== -1) {
streamBegin = connEnd + 1;
} else {
// If there's not a '&', we use the last '/' as the delimiter.
connEnd = streamBegin = src.lastIndexOf('/') + 1;
if (connEnd === 0) {
// really, there's not a '/'?
connEnd = streamBegin = src.length;
}
}
parts.connection = src.substring(0, connEnd);
parts.stream = src.substring(streamBegin, src.length);
return parts;
};
Flash.isStreamingType = function (srcType) {
return srcType in Flash.streamingFormats;
};
// RTMP has four variations, any string starting
// with one of these protocols should be valid
Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
Flash.isStreamingSrc = function (src) {
return Flash.RTMP_RE.test(src);
};
/**
* A source handler for RTMP urls
* @type {Object}
*/
Flash.rtmpSourceHandler = {};
/**
* Check if Flash can play the given videotype
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canPlayType = function (type) {
if (Flash.isStreamingType(type)) {
return 'maybe';
}
return '';
};
/**
* Check if Flash can handle the source natively
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canHandleSource = function (source) {
var can = Flash.rtmpSourceHandler.canPlayType(source.type);
if (can) {
return can;
}
if (Flash.isStreamingSrc(source.src)) {
return 'maybe';
}
return '';
};
/**
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.rtmpSourceHandler.handleSource = function (source, tech) {
var srcParts = Flash.streamToParts(source.src);
tech['setRtmpConnection'](srcParts.connection);
tech['setRtmpStream'](srcParts.stream);
};
// Register the native source handler
Flash.registerSourceHandler(Flash.rtmpSourceHandler);
return Flash;
}
exports['default'] = FlashRtmpDecorator;
module.exports = exports['default'];
},{}],112:[function(_dereq_,module,exports){
/**
* @file flash.js
* VideoJS-SWF - Custom Flash Player with HTML5-ish API
* https://github.com/zencoder/video-js-swf
* Not using setupTriggers. Using global onEvent func to distribute events
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _tech = _dereq_('./tech');
var _tech2 = _interopRequireDefault(_tech);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _flashRtmp = _dereq_('./flash-rtmp');
var _flashRtmp2 = _interopRequireDefault(_flashRtmp);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var navigator = _globalWindow2['default'].navigator;
/**
* Flash Media Controller - Wrapper for fallback SWF API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Flash
*/
var Flash = (function (_Tech) {
_inherits(Flash, _Tech);
function Flash(options, ready) {
_classCallCheck(this, Flash);
_Tech.call(this, options, ready);
// Set the source when ready
if (options.source) {
this.ready(function () {
this.setSource(options.source);
}, true);
}
// Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers
// This allows resetting the playhead when we catch the reload
if (options.startTime) {
this.ready(function () {
this.load();
this.play();
this.currentTime(options.startTime);
}, true);
}
// Add global window functions that the swf expects
// A 4.x workflow we weren't able to solve for in 5.0
// because of the need to hard code these functions
// into the swf for security reasons
_globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {};
_globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {};
_globalWindow2['default'].videojs.Flash.onReady = Flash.onReady;
_globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent;
_globalWindow2['default'].videojs.Flash.onError = Flash.onError;
this.on('seeked', function () {
this.lastSeekTarget_ = undefined;
});
}
// Create setters and getters for attributes
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Flash.prototype.createEl = function createEl() {
var options = this.options_;
// If video.js is hosted locally you should also set the location
// for the hosted swf, which should be relative to the page (not video.js)
// Otherwise this adds a CDN url.
// The CDN also auto-adds a swf URL for that specific version.
if (!options.swf) {
options.swf = '//vjs.zencdn.net/swf/5.0.1/video-js.swf';
}
// Generate ID for swf object
var objId = options.techId;
// Merge default flashvars with ones passed in to init
var flashVars = _objectAssign2['default']({
// SWF Callback Functions
'readyFunction': 'videojs.Flash.onReady',
'eventProxyFunction': 'videojs.Flash.onEvent',
'errorEventProxyFunction': 'videojs.Flash.onError',
// Player Settings
'autoplay': options.autoplay,
'preload': options.preload,
'loop': options.loop,
'muted': options.muted
}, options.flashVars);
// Merge default parames with ones passed in
var params = _objectAssign2['default']({
'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance
'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading
}, options.params);
// Merge default attributes with ones passed in
var attributes = _objectAssign2['default']({
'id': objId,
'name': objId, // Both ID and Name needed or swf to identify itself
'class': 'vjs-tech'
}, options.attributes);
this.el_ = Flash.embed(options.swf, flashVars, params, attributes);
this.el_.tech = this;
return this.el_;
};
/**
* Play for flash tech
*
* @method play
*/
Flash.prototype.play = function play() {
if (this.ended()) {
this.setCurrentTime(0);
}
this.el_.vjs_play();
};
/**
* Pause for flash tech
*
* @method pause
*/
Flash.prototype.pause = function pause() {
this.el_.vjs_pause();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Flash.prototype.src = function src(_src) {
if (_src === undefined) {
return this.currentSrc();
}
// Setting src through `src` not `setSrc` will be deprecated
return this.setSrc(_src);
};
/**
* Set video
*
* @param {Object=} src Source object
* @deprecated
* @method setSrc
*/
Flash.prototype.setSrc = function setSrc(src) {
// Make sure source URL is absolute.
src = Url.getAbsoluteURL(src);
this.el_.vjs_src(src);
// Currently the SWF doesn't autoplay if you load a source later.
// e.g. Load player w/ no source, wait 2s, set src.
if (this.autoplay()) {
var tech = this;
this.setTimeout(function () {
tech.play();
}, 0);
}
};
/**
* Returns true if the tech is currently seeking.
* @return {boolean} true if seeking
*/
Flash.prototype.seeking = function seeking() {
return this.lastSeekTarget_ !== undefined;
};
/**
* Set current time
*
* @param {Number} time Current time of video
* @method setCurrentTime
*/
Flash.prototype.setCurrentTime = function setCurrentTime(time) {
var seekable = this.seekable();
if (seekable.length) {
// clamp to the current seekable range
time = time > seekable.start(0) ? time : seekable.start(0);
time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1);
this.lastSeekTarget_ = time;
this.trigger('seeking');
this.el_.vjs_setProperty('currentTime', time);
_Tech.prototype.setCurrentTime.call(this);
}
};
/**
* Get current time
*
* @param {Number=} time Current time of video
* @return {Number} Current time
* @method currentTime
*/
Flash.prototype.currentTime = function currentTime(time) {
// when seeking make the reported time keep up with the requested time
// by reading the time we're seeking to
if (this.seeking()) {
return this.lastSeekTarget_ || 0;
}
return this.el_.vjs_getProperty('currentTime');
};
/**
* Get current source
*
* @method currentSrc
*/
Flash.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
} else {
return this.el_.vjs_getProperty('currentSrc');
}
};
/**
* Load media into player
*
* @method load
*/
Flash.prototype.load = function load() {
this.el_.vjs_load();
};
/**
* Get poster
*
* @method poster
*/
Flash.prototype.poster = function poster() {
this.el_.vjs_getProperty('poster');
};
/**
* Poster images are not handled by the Flash tech so make this a no-op
*
* @method setPoster
*/
Flash.prototype.setPoster = function setPoster() {};
/**
* Determine if can seek in media
*
* @return {TimeRangeObject}
* @method seekable
*/
Flash.prototype.seekable = function seekable() {
var duration = this.duration();
if (duration === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(0, duration);
};
/**
* Get buffered time range
*
* @return {TimeRangeObject}
* @method buffered
*/
Flash.prototype.buffered = function buffered() {
var ranges = this.el_.vjs_getProperty('buffered');
if (ranges.length === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]);
};
/**
* Get fullscreen support -
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method supportsFullScreen
*/
Flash.prototype.supportsFullScreen = function supportsFullScreen() {
return false; // Flash does not allow fullscreen through javascript
};
/**
* Request to enter fullscreen
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method enterFullScreen
*/
Flash.prototype.enterFullScreen = function enterFullScreen() {
return false;
};
return Flash;
})(_tech2['default']);
var _api = Flash.prototype;
var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(',');
var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(',');
function _createSetter(attr) {
var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
_api['set' + attrUpper] = function (val) {
return this.el_.vjs_setProperty(attr, val);
};
}
function _createGetter(attr) {
_api[attr] = function () {
return this.el_.vjs_getProperty(attr);
};
}
// Create getter and setters for all read/write attributes
for (var i = 0; i < _readWrite.length; i++) {
_createGetter(_readWrite[i]);
_createSetter(_readWrite[i]);
}
// Create getters for read-only attributes
for (var i = 0; i < _readOnly.length; i++) {
_createGetter(_readOnly[i]);
}
/* Flash Support Testing -------------------------------------------------------- */
Flash.isSupported = function () {
return Flash.version()[0] >= 10;
// return swfobject.hasFlashPlayerVersion('10');
};
// Add Source Handler pattern functions to this tech
_tech2['default'].withSourceHandlers(Flash);
/*
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
*
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler = {};
/**
* Check if Flash can play the given videotype
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.nativeSourceHandler.canPlayType = function (type) {
if (type in Flash.formats) {
return 'maybe';
}
return '';
};
/*
* Check Flash can handle the source natively
*
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.nativeSourceHandler.canHandleSource = function (source) {
var type;
function guessMimeType(src) {
var ext = Url.getFileExtension(src);
if (ext) {
return 'video/' + ext;
}
return '';
}
if (!source.type) {
type = guessMimeType(source.src);
} else {
// Strip code information from the type because we don't get that specific
type = source.type.replace(/;.*/, '').toLowerCase();
}
return Flash.nativeSourceHandler.canPlayType(type);
};
/*
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
*
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/*
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Flash.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Flash.registerSourceHandler(Flash.nativeSourceHandler);
Flash.formats = {
'video/flv': 'FLV',
'video/x-flv': 'FLV',
'video/mp4': 'MP4',
'video/m4v': 'MP4'
};
Flash.onReady = function (currSwf) {
var el = Dom.getEl(currSwf);
var tech = el && el.tech;
// if there is no el then the tech has been disposed
// and the tech element was removed from the player div
if (tech && tech.el()) {
// check that the flash object is really ready
Flash.checkReady(tech);
}
};
// The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object.
// If it's not ready, we set a timeout to check again shortly.
Flash.checkReady = function (tech) {
// stop worrying if the tech has been disposed
if (!tech.el()) {
return;
}
// check if API property exists
if (tech.el().vjs_getProperty) {
// tell tech it's ready
tech.triggerReady();
} else {
// wait longer
this.setTimeout(function () {
Flash['checkReady'](tech);
}, 50);
}
};
// Trigger events from the swf on the player
Flash.onEvent = function (swfID, eventName) {
var tech = Dom.getEl(swfID).tech;
tech.trigger(eventName);
};
// Log errors from the swf
Flash.onError = function (swfID, err) {
var tech = Dom.getEl(swfID).tech;
// trigger MEDIA_ERR_SRC_NOT_SUPPORTED
if (err === 'srcnotfound') {
return tech.error(4);
}
// trigger a custom error
tech.error('FLASH: ' + err);
};
// Flash Version Check
Flash.version = function () {
var version = '0,0,0';
// IE
try {
version = new _globalWindow2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
// other browsers
} catch (e) {
try {
if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
}
} catch (err) {}
}
return version.split(',');
};
// Flash embedding method. Only used in non-iframe mode
Flash.embed = function (swf, flashVars, params, attributes) {
var code = Flash.getEmbedCode(swf, flashVars, params, attributes);
// Get element by embedding code and retrieving created element
var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0];
return obj;
};
Flash.getEmbedCode = function (swf, flashVars, params, attributes) {
var objTag = '<object type="application/x-shockwave-flash" ';
var flashVarsString = '';
var paramsString = '';
var attrsString = '';
// Convert flash vars to string
if (flashVars) {
Object.getOwnPropertyNames(flashVars).forEach(function (key) {
flashVarsString += key + '=' + flashVars[key] + '&';
});
}
// Add swf, flashVars, and other default params
params = _objectAssign2['default']({
'movie': swf,
'flashvars': flashVarsString,
'allowScriptAccess': 'always', // Required to talk to swf
'allowNetworking': 'all' // All should be default, but having security issues.
}, params);
// Create param tags string
Object.getOwnPropertyNames(params).forEach(function (key) {
paramsString += '<param name="' + key + '" value="' + params[key] + '" />';
});
attributes = _objectAssign2['default']({
// Add swf to attributes (need both for IE and Others to work)
'data': swf,
// Default to 100% width/height
'width': '100%',
'height': '100%'
}, attributes);
// Create Attributes string
Object.getOwnPropertyNames(attributes).forEach(function (key) {
attrsString += key + '="' + attributes[key] + '" ';
});
return '' + objTag + attrsString + '>' + paramsString + '</object>';
};
// Run Flash through the RTMP decorator
_flashRtmp2['default'](Flash);
_component2['default'].registerComponent('Flash', Flash);
_tech2['default'].registerTech('Flash', Flash);
exports['default'] = Flash;
module.exports = exports['default'];
},{"../component":65,"../utils/dom.js":128,"../utils/time-ranges.js":136,"../utils/url.js":138,"./flash-rtmp":111,"./tech":115,"global/window":2,"object.assign":45}],113:[function(_dereq_,module,exports){
/**
* @file html5.js
* HTML5 Media Controller - Wrapper for HTML5 Media API
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _techJs = _dereq_('./tech.js');
var _techJs2 = _interopRequireDefault(_techJs);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Html5
*/
var Html5 = (function (_Tech) {
_inherits(Html5, _Tech);
function Html5(options, ready) {
_classCallCheck(this, Html5);
_Tech.call(this, options, ready);
var source = options.source;
// Set the source if one is provided
// 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
// 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
// anyway so the error gets fired.
if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
this.setSource(source);
} else {
this.handleLateInit_(this.el_);
}
if (this.el_.hasChildNodes()) {
var nodes = this.el_.childNodes;
var nodesLength = nodes.length;
var removeNodes = [];
while (nodesLength--) {
var node = nodes[nodesLength];
var nodeName = node.nodeName.toLowerCase();
if (nodeName === 'track') {
if (!this.featuresNativeTextTracks) {
// Empty video tag tracks so the built-in player doesn't use them also.
// This may not be fast enough to stop HTML5 browsers from reading the tags
// so we'll need to turn off any default tracks if we're manually doing
// captions and subtitles. videoElement.textTracks
removeNodes.push(node);
} else {
// store HTMLTrackElement and TextTrack to remote list
this.remoteTextTrackEls().addTrackElement_(node);
this.remoteTextTracks().addTrack_(node.track);
}
}
}
for (var i = 0; i < removeNodes.length; i++) {
this.el_.removeChild(removeNodes[i]);
}
}
if (this.featuresNativeTextTracks) {
this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange);
this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd);
this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove);
this.proxyNativeTextTracks_();
}
// Determine if native controls should be used
// Our goal should be to get the custom controls on mobile solid everywhere
// so we can remove this all together. Right now this will block custom
// controls on touch enabled laptops like the Chrome Pixel
if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) {
this.setControls(true);
}
this.triggerReady();
}
/* HTML5 Support Testing ---------------------------------------------------- */
/*
* Element for testing browser HTML5 video capabilities
*
* @type {Element}
* @constant
* @private
*/
/**
* Dispose of html5 media element
*
* @method dispose
*/
Html5.prototype.dispose = function dispose() {
var tt = this.el().textTracks;
var emulatedTt = this.textTracks();
// remove native event listeners
if (tt && tt.removeEventListener) {
tt.removeEventListener('change', this.handleTextTrackChange_);
tt.removeEventListener('addtrack', this.handleTextTrackAdd_);
tt.removeEventListener('removetrack', this.handleTextTrackRemove_);
}
// clearout the emulated text track list.
var i = emulatedTt.length;
while (i--) {
emulatedTt.removeTrack_(emulatedTt[i]);
}
Html5.disposeMediaElement(this.el_);
_Tech.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Html5.prototype.createEl = function createEl() {
var el = this.options_.tag;
// Check if this browser supports moving the element into the box.
// On the iPhone video will break if you move the element,
// So we have to create a brand new element.
if (!el || this['movingMediaElementInDOM'] === false) {
// If the original tag is still there, clone and remove it.
if (el) {
var clone = el.cloneNode(true);
el.parentNode.insertBefore(clone, el);
Html5.disposeMediaElement(el);
el = clone;
} else {
el = _globalDocument2['default'].createElement('video');
// determine if native controls should be used
var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag);
var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes);
if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
delete attributes.controls;
}
Dom.setElAttributes(el, _objectAssign2['default'](attributes, {
id: this.options_.techId,
'class': 'vjs-tech'
}));
}
}
// Update specific tag settings, in case they were overridden
var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted'];
for (var i = settingsAttrs.length - 1; i >= 0; i--) {
var attr = settingsAttrs[i];
var overwriteAttrs = {};
if (typeof this.options_[attr] !== 'undefined') {
overwriteAttrs[attr] = this.options_[attr];
}
Dom.setElAttributes(el, overwriteAttrs);
}
return el;
// jenniisawesome = true;
};
// If we're loading the playback object after it has started loading
// or playing the video (often with autoplay on) then the loadstart event
// has already fired and we need to fire it manually because many things
// rely on it.
Html5.prototype.handleLateInit_ = function handleLateInit_(el) {
var _this = this;
if (el.networkState === 0 || el.networkState === 3) {
// The video element hasn't started loading the source yet
// or didn't find a source
return;
}
if (el.readyState === 0) {
var _ret = (function () {
// NetworkState is set synchronously BUT loadstart is fired at the
// end of the current stack, usually before setInterval(fn, 0).
// So at this point we know loadstart may have already fired or is
// about to fire, and either way the player hasn't seen it yet.
// We don't want to fire loadstart prematurely here and cause a
// double loadstart so we'll wait and see if it happens between now
// and the next loop, and fire it if not.
// HOWEVER, we also want to make sure it fires before loadedmetadata
// which could also happen between now and the next loop, so we'll
// watch for that also.
var loadstartFired = false;
var setLoadstartFired = function setLoadstartFired() {
loadstartFired = true;
};
_this.on('loadstart', setLoadstartFired);
var triggerLoadstart = function triggerLoadstart() {
// We did miss the original loadstart. Make sure the player
// sees loadstart before loadedmetadata
if (!loadstartFired) {
this.trigger('loadstart');
}
};
_this.on('loadedmetadata', triggerLoadstart);
_this.ready(function () {
this.off('loadstart', setLoadstartFired);
this.off('loadedmetadata', triggerLoadstart);
if (!loadstartFired) {
// We did miss the original native loadstart. Fire it now.
this.trigger('loadstart');
}
});
return {
v: undefined
};
})();
if (typeof _ret === 'object') return _ret.v;
}
// From here on we know that loadstart already fired and we missed it.
// The other readyState events aren't as much of a problem if we double
// them, so not going to go to as much trouble as loadstart to prevent
// that unless we find reason to.
var eventsToTrigger = ['loadstart'];
// loadedmetadata: newly equal to HAVE_METADATA (1) or greater
eventsToTrigger.push('loadedmetadata');
// loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
if (el.readyState >= 2) {
eventsToTrigger.push('loadeddata');
}
// canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
if (el.readyState >= 3) {
eventsToTrigger.push('canplay');
}
// canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
if (el.readyState >= 4) {
eventsToTrigger.push('canplaythrough');
}
// We still need to give the player time to add event listeners
this.ready(function () {
eventsToTrigger.forEach(function (type) {
this.trigger(type);
}, this);
});
};
Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() {
var tt = this.el().textTracks;
if (tt && tt.addEventListener) {
tt.addEventListener('change', this.handleTextTrackChange_);
tt.addEventListener('addtrack', this.handleTextTrackAdd_);
tt.addEventListener('removetrack', this.handleTextTrackRemove_);
}
};
Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) {
var tt = this.textTracks();
this.textTracks().trigger({
type: 'change',
target: tt,
currentTarget: tt,
srcElement: tt
});
};
Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) {
this.textTracks().addTrack_(e.track);
};
Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) {
this.textTracks().removeTrack_(e.track);
};
/**
* Play for html5 tech
*
* @method play
*/
Html5.prototype.play = function play() {
this.el_.play();
};
/**
* Pause for html5 tech
*
* @method pause
*/
Html5.prototype.pause = function pause() {
this.el_.pause();
};
/**
* Paused for html5 tech
*
* @return {Boolean}
* @method paused
*/
Html5.prototype.paused = function paused() {
return this.el_.paused;
};
/**
* Get current time
*
* @return {Number}
* @method currentTime
*/
Html5.prototype.currentTime = function currentTime() {
return this.el_.currentTime;
};
/**
* Set current time
*
* @param {Number} seconds Current time of video
* @method setCurrentTime
*/
Html5.prototype.setCurrentTime = function setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
_utilsLogJs2['default'](e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
};
/**
* Get duration
*
* @return {Number}
* @method duration
*/
Html5.prototype.duration = function duration() {
return this.el_.duration || 0;
};
/**
* Get a TimeRange object that represents the intersection
* of the time ranges for which the user agent has all
* relevant media
*
* @return {TimeRangeObject}
* @method buffered
*/
Html5.prototype.buffered = function buffered() {
return this.el_.buffered;
};
/**
* Get volume level
*
* @return {Number}
* @method volume
*/
Html5.prototype.volume = function volume() {
return this.el_.volume;
};
/**
* Set volume level
*
* @param {Number} percentAsDecimal Volume percent as a decimal
* @method setVolume
*/
Html5.prototype.setVolume = function setVolume(percentAsDecimal) {
this.el_.volume = percentAsDecimal;
};
/**
* Get if muted
*
* @return {Boolean}
* @method muted
*/
Html5.prototype.muted = function muted() {
return this.el_.muted;
};
/**
* Set muted
*
* @param {Boolean} If player is to be muted or note
* @method setMuted
*/
Html5.prototype.setMuted = function setMuted(muted) {
this.el_.muted = muted;
};
/**
* Get player width
*
* @return {Number}
* @method width
*/
Html5.prototype.width = function width() {
return this.el_.offsetWidth;
};
/**
* Get player height
*
* @return {Number}
* @method height
*/
Html5.prototype.height = function height() {
return this.el_.offsetHeight;
};
/**
* Get if there is fullscreen support
*
* @return {Boolean}
* @method supportsFullScreen
*/
Html5.prototype.supportsFullScreen = function supportsFullScreen() {
if (typeof this.el_.webkitEnterFullScreen === 'function') {
var userAgent = _globalWindow2['default'].navigator.userAgent;
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
return true;
}
}
return false;
};
/**
* Request to enter fullscreen
*
* @method enterFullScreen
*/
Html5.prototype.enterFullScreen = function enterFullScreen() {
var video = this.el_;
if ('webkitDisplayingFullscreen' in video) {
this.one('webkitbeginfullscreen', function () {
this.one('webkitendfullscreen', function () {
this.trigger('fullscreenchange', { isFullscreen: false });
});
this.trigger('fullscreenchange', { isFullscreen: true });
});
}
if (video.paused && video.networkState <= video.HAVE_METADATA) {
// attempt to prime the video element for programmatic access
// this isn't necessary on the desktop but shouldn't hurt
this.el_.play();
// playing and pausing synchronously during the transition to fullscreen
// can get iOS ~6.1 devices into a play/pause loop
this.setTimeout(function () {
video.pause();
video.webkitEnterFullScreen();
}, 0);
} else {
video.webkitEnterFullScreen();
}
};
/**
* Request to exit fullscreen
*
* @method exitFullScreen
*/
Html5.prototype.exitFullScreen = function exitFullScreen() {
this.el_.webkitExitFullScreen();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Html5.prototype.src = function src(_src) {
if (_src === undefined) {
return this.el_.src;
} else {
// Setting src through `src` instead of `setSrc` will be deprecated
this.setSrc(_src);
}
};
/**
* Set video
*
* @param {Object} src Source object
* @deprecated
* @method setSrc
*/
Html5.prototype.setSrc = function setSrc(src) {
this.el_.src = src;
};
/**
* Load media into player
*
* @method load
*/
Html5.prototype.load = function load() {
this.el_.load();
};
/**
* Reset the tech. Removes all sources and calls `load`.
*
* @method reset
*/
Html5.prototype.reset = function reset() {
Html5.resetMediaElement(this.el_);
};
/**
* Get current source
*
* @return {Object}
* @method currentSrc
*/
Html5.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
} else {
return this.el_.currentSrc;
}
};
/**
* Get poster
*
* @return {String}
* @method poster
*/
Html5.prototype.poster = function poster() {
return this.el_.poster;
};
/**
* Set poster
*
* @param {String} val URL to poster image
* @method
*/
Html5.prototype.setPoster = function setPoster(val) {
this.el_.poster = val;
};
/**
* Get preload attribute
*
* @return {String}
* @method preload
*/
Html5.prototype.preload = function preload() {
return this.el_.preload;
};
/**
* Set preload attribute
*
* @param {String} val Value for preload attribute
* @method setPreload
*/
Html5.prototype.setPreload = function setPreload(val) {
this.el_.preload = val;
};
/**
* Get autoplay attribute
*
* @return {String}
* @method autoplay
*/
Html5.prototype.autoplay = function autoplay() {
return this.el_.autoplay;
};
/**
* Set autoplay attribute
*
* @param {String} val Value for preload attribute
* @method setAutoplay
*/
Html5.prototype.setAutoplay = function setAutoplay(val) {
this.el_.autoplay = val;
};
/**
* Get controls attribute
*
* @return {String}
* @method controls
*/
Html5.prototype.controls = function controls() {
return this.el_.controls;
};
/**
* Set controls attribute
*
* @param {String} val Value for controls attribute
* @method setControls
*/
Html5.prototype.setControls = function setControls(val) {
this.el_.controls = !!val;
};
/**
* Get loop attribute
*
* @return {String}
* @method loop
*/
Html5.prototype.loop = function loop() {
return this.el_.loop;
};
/**
* Set loop attribute
*
* @param {String} val Value for loop attribute
* @method setLoop
*/
Html5.prototype.setLoop = function setLoop(val) {
this.el_.loop = val;
};
/**
* Get error value
*
* @return {String}
* @method error
*/
Html5.prototype.error = function error() {
return this.el_.error;
};
/**
* Get whether or not the player is in the "seeking" state
*
* @return {Boolean}
* @method seeking
*/
Html5.prototype.seeking = function seeking() {
return this.el_.seeking;
};
/**
* Get a TimeRanges object that represents the
* ranges of the media resource to which it is possible
* for the user agent to seek.
*
* @return {TimeRangeObject}
* @method seekable
*/
Html5.prototype.seekable = function seekable() {
return this.el_.seekable;
};
/**
* Get if video ended
*
* @return {Boolean}
* @method ended
*/
Html5.prototype.ended = function ended() {
return this.el_.ended;
};
/**
* Get the value of the muted content attribute
* This attribute has no dynamic effect, it only
* controls the default state of the element
*
* @return {Boolean}
* @method defaultMuted
*/
Html5.prototype.defaultMuted = function defaultMuted() {
return this.el_.defaultMuted;
};
/**
* Get desired speed at which the media resource is to play
*
* @return {Number}
* @method playbackRate
*/
Html5.prototype.playbackRate = function playbackRate() {
return this.el_.playbackRate;
};
/**
* Returns a TimeRanges object that represents the ranges of the
* media resource that the user agent has played.
* @return {TimeRangeObject} the range of points on the media
* timeline that has been reached through normal playback
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played
*/
Html5.prototype.played = function played() {
return this.el_.played;
};
/**
* Set desired speed at which the media resource is to play
*
* @param {Number} val Speed at which the media resource is to play
* @method setPlaybackRate
*/
Html5.prototype.setPlaybackRate = function setPlaybackRate(val) {
this.el_.playbackRate = val;
};
/**
* Get the current state of network activity for the element, from
* the list below
* NETWORK_EMPTY (numeric value 0)
* NETWORK_IDLE (numeric value 1)
* NETWORK_LOADING (numeric value 2)
* NETWORK_NO_SOURCE (numeric value 3)
*
* @return {Number}
* @method networkState
*/
Html5.prototype.networkState = function networkState() {
return this.el_.networkState;
};
/**
* Get a value that expresses the current state of the element
* with respect to rendering the current playback position, from
* the codes in the list below
* HAVE_NOTHING (numeric value 0)
* HAVE_METADATA (numeric value 1)
* HAVE_CURRENT_DATA (numeric value 2)
* HAVE_FUTURE_DATA (numeric value 3)
* HAVE_ENOUGH_DATA (numeric value 4)
*
* @return {Number}
* @method readyState
*/
Html5.prototype.readyState = function readyState() {
return this.el_.readyState;
};
/**
* Get width of video
*
* @return {Number}
* @method videoWidth
*/
Html5.prototype.videoWidth = function videoWidth() {
return this.el_.videoWidth;
};
/**
* Get height of video
*
* @return {Number}
* @method videoHeight
*/
Html5.prototype.videoHeight = function videoHeight() {
return this.el_.videoHeight;
};
/**
* Get text tracks
*
* @return {TextTrackList}
* @method textTracks
*/
Html5.prototype.textTracks = function textTracks() {
return _Tech.prototype.textTracks.call(this);
};
/**
* Creates and returns a text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addTextTrack.call(this, kind, label, language);
}
return this.el_.addTextTrack(kind, label, language);
};
/**
* Creates a remote text track object and returns a html track element
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {HTMLTrackElement}
* @method addRemoteTextTrack
*/
Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addRemoteTextTrack.call(this, options);
}
var htmlTrackElement = _globalDocument2['default'].createElement('track');
if (options.kind) {
htmlTrackElement.kind = options.kind;
}
if (options.label) {
htmlTrackElement.label = options.label;
}
if (options.language || options.srclang) {
htmlTrackElement.srclang = options.language || options.srclang;
}
if (options['default']) {
htmlTrackElement['default'] = options['default'];
}
if (options.id) {
htmlTrackElement.id = options.id;
}
if (options.src) {
htmlTrackElement.src = options.src;
}
this.el().appendChild(htmlTrackElement);
// store HTMLTrackElement and TextTrack to remote list
this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
this.remoteTextTracks().addTrack_(htmlTrackElement.track);
return htmlTrackElement;
};
/**
* Remove remote text track from TextTrackList object
*
* @param {TextTrackObject} track Texttrack object to remove
* @method removeRemoteTextTrack
*/
Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.removeRemoteTextTrack.call(this, track);
}
var tracks = undefined,
i = undefined;
var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
// remove HTMLTrackElement and TextTrack from remote list
this.remoteTextTrackEls().removeTrackElement_(trackElement);
this.remoteTextTracks().removeTrack_(track);
tracks = this.$$('track');
i = tracks.length;
while (i--) {
if (track === tracks[i] || track === tracks[i].track) {
this.el().removeChild(tracks[i]);
}
}
};
return Html5;
})(_techJs2['default']);
Html5.TEST_VID = _globalDocument2['default'].createElement('video');
var track = _globalDocument2['default'].createElement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'English';
Html5.TEST_VID.appendChild(track);
/*
* Check if HTML5 video is supported by this browser/device
*
* @return {Boolean}
*/
Html5.isSupported = function () {
// IE9 with no Media Player is a LIAR! (#984)
try {
Html5.TEST_VID['volume'] = 0.5;
} catch (e) {
return false;
}
return !!Html5.TEST_VID.canPlayType;
};
// Add Source Handler pattern functions to this tech
_techJs2['default'].withSourceHandlers(Html5);
/*
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
*
* @param {Object} source The source object
* @param {Html5} tech The instance of the HTML5 tech
*/
Html5.nativeSourceHandler = {};
/*
* Check if the video element can play the given videotype
*
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Html5.nativeSourceHandler.canPlayType = function (type) {
// IE9 on Windows 7 without MediaPlayer throws an error here
// https://github.com/videojs/video.js/issues/519
try {
return Html5.TEST_VID.canPlayType(type);
} catch (e) {
return '';
}
};
/*
* Check if the video element can handle the source natively
*
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Html5.nativeSourceHandler.canHandleSource = function (source) {
var match, ext;
// If a type was provided we should rely on that
if (source.type) {
return Html5.nativeSourceHandler.canPlayType(source.type);
} else if (source.src) {
// If no type, fall back to checking 'video/[EXTENSION]'
ext = Url.getFileExtension(source.src);
return Html5.nativeSourceHandler.canPlayType('video/' + ext);
}
return '';
};
/*
* Pass the source to the video element
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
*
* @param {Object} source The source object
* @param {Html5} tech The instance of the Html5 tech
*/
Html5.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/*
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Html5.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Html5.registerSourceHandler(Html5.nativeSourceHandler);
/*
* Check if the volume can be changed in this browser/device.
* Volume cannot be changed in a lot of mobile devices.
* Specifically, it can't be changed from 1 on iOS.
*
* @return {Boolean}
*/
Html5.canControlVolume = function () {
var volume = Html5.TEST_VID.volume;
Html5.TEST_VID.volume = volume / 2 + 0.1;
return volume !== Html5.TEST_VID.volume;
};
/*
* Check if playbackRate is supported in this browser/device.
*
* @return {Number} [description]
*/
Html5.canControlPlaybackRate = function () {
var playbackRate = Html5.TEST_VID.playbackRate;
Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
return playbackRate !== Html5.TEST_VID.playbackRate;
};
/*
* Check to see if native text tracks are supported by this browser/device
*
* @return {Boolean}
*/
Html5.supportsNativeTextTracks = function () {
var supportsTextTracks;
// Figure out native text track support
// If mode is a number, we cannot change it because it'll disappear from view.
// Browsers with numeric modes include IE10 and older (<=2013) samsung android models.
// Firefox isn't playing nice either with modifying the mode
// TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862
supportsTextTracks = !!Html5.TEST_VID.textTracks;
if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) {
supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number';
}
if (supportsTextTracks && browser.IS_FIREFOX) {
supportsTextTracks = false;
}
if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) {
supportsTextTracks = false;
}
return supportsTextTracks;
};
/**
* An array of events available on the Html5 tech.
*
* @private
* @type {Array}
*/
Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange'];
/*
* Set the tech's volume control support status
*
* @type {Boolean}
*/
Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume();
/*
* Set the tech's playbackRate support status
*
* @type {Boolean}
*/
Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate();
/*
* Set the tech's status on moving the video element.
* In iOS, if you move a video element in the DOM, it breaks video playback.
*
* @type {Boolean}
*/
Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS;
/*
* Set the the tech's fullscreen resize support status.
* HTML video is able to automatically resize when going to fullscreen.
* (No longer appears to be used. Can probably be removed.)
*/
Html5.prototype['featuresFullscreenResize'] = true;
/*
* Set the tech's progress event support status
* (this disables the manual progress events of the Tech)
*/
Html5.prototype['featuresProgressEvents'] = true;
/*
* Sets the tech's status on native text track support
*
* @type {Boolean}
*/
Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks();
// HTML5 Feature detection and Device Fixes --------------------------------- //
var canPlayType = undefined;
var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
var mp4RE = /^video\/mp4/i;
Html5.patchCanPlayType = function () {
// Android 4.0 and above can play HLS to some extent but it reports being unable to do so
if (browser.ANDROID_VERSION >= 4.0) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mpegurlRE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
// Override Android 2.2 and less canPlayType method which is broken
if (browser.IS_OLD_ANDROID) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
Html5.unpatchCanPlayType = function () {
var r = Html5.TEST_VID.constructor.prototype.canPlayType;
Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
canPlayType = null;
return r;
};
// by default, patch the video element
Html5.patchCanPlayType();
Html5.disposeMediaElement = function (el) {
if (!el) {
return;
}
if (el.parentNode) {
el.parentNode.removeChild(el);
}
// remove any child track or source nodes to prevent their loading
while (el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
// remove any src reference. not setting `src=''` because that causes a warning
// in firefox
el.removeAttribute('src');
// force the media element to update its loading state by calling load()
// however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {
// not supported
}
})();
}
};
Html5.resetMediaElement = function (el) {
if (!el) {
return;
}
var sources = el.querySelectorAll('source');
var i = sources.length;
while (i--) {
el.removeChild(sources[i]);
}
// remove any src reference.
// not setting `src=''` because that throws an error
el.removeAttribute('src');
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {}
})();
}
};
_component2['default'].registerComponent('Html5', Html5);
_techJs2['default'].registerTech('Html5', Html5);
exports['default'] = Html5;
module.exports = exports['default'];
},{"../component":65,"../utils/browser.js":125,"../utils/dom.js":128,"../utils/fn.js":130,"../utils/log.js":133,"../utils/merge-options.js":134,"../utils/url.js":138,"./tech.js":115,"global/document":1,"global/window":2,"object.assign":45}],114:[function(_dereq_,module,exports){
/**
* @file loader.js
*/
'use strict';
exports.__esModule = true;
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 _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _techJs = _dereq_('./tech.js');
var _techJs2 = _interopRequireDefault(_techJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* The Media Loader is the component that decides which playback technology to load
* when the player is initialized.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class MediaLoader
*/
var MediaLoader = (function (_Component) {
_inherits(MediaLoader, _Component);
function MediaLoader(player, options, ready) {
_classCallCheck(this, MediaLoader);
_Component.call(this, player, options, ready);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) {
for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) {
var techName = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _techJs2['default'].getTech(techName);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!techName) {
tech = _componentJs2['default'].getComponent(techName);
}
// Check if the browser supports this technology
if (tech && tech.isSupported()) {
player.loadTech_(techName);
break;
}
}
} else {
// // Loop through playback technologies (HTML5, Flash) and check for support.
// // Then load the best source.
// // A few assumptions here:
// // All playback technologies respect preload false.
player.src(options.playerOptions['sources']);
}
}
return MediaLoader;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('MediaLoader', MediaLoader);
exports['default'] = MediaLoader;
module.exports = exports['default'];
},{"../component.js":65,"../utils/to-title-case.js":137,"./tech.js":115,"global/window":2}],115:[function(_dereq_,module,exports){
/**
* @file tech.js
* Media Technology Controller - Base class for media playback
* technology controllers like Flash and HTML5
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _tracksHtmlTrackElement = _dereq_('../tracks/html-track-element');
var _tracksHtmlTrackElement2 = _interopRequireDefault(_tracksHtmlTrackElement);
var _tracksHtmlTrackElementList = _dereq_('../tracks/html-track-element-list');
var _tracksHtmlTrackElementList2 = _interopRequireDefault(_tracksHtmlTrackElementList);
var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
var _tracksTextTrack = _dereq_('../tracks/text-track');
var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack);
var _tracksTextTrackList = _dereq_('../tracks/text-track-list');
var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _utilsBufferJs = _dereq_('../utils/buffer.js');
var _mediaErrorJs = _dereq_('../media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Base class for media (HTML5 Video, Flash) controllers
*
* @param {Object=} options Options object
* @param {Function=} ready Ready callback function
* @extends Component
* @class Tech
*/
var Tech = (function (_Component) {
_inherits(Tech, _Component);
function Tech() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1];
_classCallCheck(this, Tech);
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
_Component.call(this, null, options, ready);
// keep track of whether the current source has played at all to
// implement a very limited played()
this.hasStarted_ = false;
this.on('playing', function () {
this.hasStarted_ = true;
});
this.on('loadstart', function () {
this.hasStarted_ = false;
});
this.textTracks_ = options.textTracks;
// Manually track progress in cases where the browser/flash player doesn't report it.
if (!this.featuresProgressEvents) {
this.manualProgressOn();
}
// Manually track timeupdates in cases where the browser/flash player doesn't report it.
if (!this.featuresTimeupdateEvents) {
this.manualTimeUpdatesOn();
}
if (options.nativeCaptions === false || options.nativeTextTracks === false) {
this.featuresNativeTextTracks = false;
}
if (!this.featuresNativeTextTracks) {
this.on('ready', this.emulateTextTracks);
}
this.initTextTrackListeners();
// Turn on component tap events
this.emitTapEvents();
}
/*
* List of associated text tracks
*
* @type {Array}
* @private
*/
/* Fallbacks for unsupported event types
================================================================================ */
// Manually trigger progress events based on changes to the buffered amount
// Many flash players and older HTML5 browsers don't send progress or progress-like events
/**
* Turn on progress events
*
* @method manualProgressOn
*/
Tech.prototype.manualProgressOn = function manualProgressOn() {
this.on('durationchange', this.onDurationChange);
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.one('ready', this.trackProgress);
};
/**
* Turn off progress events
*
* @method manualProgressOff
*/
Tech.prototype.manualProgressOff = function manualProgressOff() {
this.manualProgress = false;
this.stopTrackingProgress();
this.off('durationchange', this.onDurationChange);
};
/**
* Track progress
*
* @method trackProgress
*/
Tech.prototype.trackProgress = function trackProgress() {
this.stopTrackingProgress();
this.progressInterval = this.setInterval(Fn.bind(this, function () {
// Don't trigger unless buffered amount is greater than last time
var numBufferedPercent = this.bufferedPercent();
if (this.bufferedPercent_ !== numBufferedPercent) {
this.trigger('progress');
}
this.bufferedPercent_ = numBufferedPercent;
if (numBufferedPercent === 1) {
this.stopTrackingProgress();
}
}), 500);
};
/**
* Update duration
*
* @method onDurationChange
*/
Tech.prototype.onDurationChange = function onDurationChange() {
this.duration_ = this.duration();
};
/**
* Create and get TimeRange object for buffering
*
* @return {TimeRangeObject}
* @method buffered
*/
Tech.prototype.buffered = function buffered() {
return _utilsTimeRangesJs.createTimeRange(0, 0);
};
/**
* Get buffered percent
*
* @return {Number}
* @method bufferedPercent
*/
Tech.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_);
};
/**
* Stops tracking progress by clearing progress interval
*
* @method stopTrackingProgress
*/
Tech.prototype.stopTrackingProgress = function stopTrackingProgress() {
this.clearInterval(this.progressInterval);
};
/*! Time Tracking -------------------------------------------------------------- */
/**
* Set event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOn
*/
Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
this.manualTimeUpdates = true;
this.on('play', this.trackCurrentTime);
this.on('pause', this.stopTrackingCurrentTime);
};
/**
* Remove event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOff
*/
Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off('play', this.trackCurrentTime);
this.off('pause', this.stopTrackingCurrentTime);
};
/**
* Tracks current time
*
* @method trackCurrentTime
*/
Tech.prototype.trackCurrentTime = function trackCurrentTime() {
if (this.currentTimeInterval) {
this.stopTrackingCurrentTime();
}
this.currentTimeInterval = this.setInterval(function () {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
};
/**
* Turn off play progress tracking (when paused or dragging)
*
* @method stopTrackingCurrentTime
*/
Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
this.clearInterval(this.currentTimeInterval);
// #1002 - if the video ends right before the next timeupdate would happen,
// the progress bar won't make it all the way to the end
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
};
/**
* Turn off any manual progress or timeupdate tracking
*
* @method dispose
*/
Tech.prototype.dispose = function dispose() {
// clear out text tracks because we can't reuse them between techs
var textTracks = this.textTracks();
if (textTracks) {
var i = textTracks.length;
while (i--) {
this.removeRemoteTextTrack(textTracks[i]);
}
}
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) {
this.manualProgressOff();
}
if (this.manualTimeUpdates) {
this.manualTimeUpdatesOff();
}
_Component.prototype.dispose.call(this);
};
/**
* Reset the tech. Removes all sources and resets readyState.
*
* @method reset
*/
Tech.prototype.reset = function reset() {};
/**
* When invoked without an argument, returns a MediaError object
* representing the current error state of the player or null if
* there is no error. When invoked with an argument, set the current
* error state of the player.
* @param {MediaError=} err Optional an error object
* @return {MediaError} the current error object or null
* @method error
*/
Tech.prototype.error = function error(err) {
if (err !== undefined) {
if (err instanceof _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['default'](err);
}
this.trigger('error');
}
return this.error_;
};
/**
* Return the time ranges that have been played through for the
* current source. This implementation is incomplete. It does not
* track the played time ranges, only whether the source has played
* at all or not.
* @return {TimeRangeObject} a single time range if this video has
* played or an empty set of ranges if not.
* @method played
*/
Tech.prototype.played = function played() {
if (this.hasStarted_) {
return _utilsTimeRangesJs.createTimeRange(0, 0);
}
return _utilsTimeRangesJs.createTimeRange();
};
/**
* Set current time
*
* @method setCurrentTime
*/
Tech.prototype.setCurrentTime = function setCurrentTime() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}
};
/**
* Initialize texttrack listeners
*
* @method initTextTrackListeners
*/
Tech.prototype.initTextTrackListeners = function initTextTrackListeners() {
var textTrackListChanges = Fn.bind(this, function () {
this.trigger('texttrackchange');
});
var tracks = this.textTracks();
if (!tracks) return;
tracks.addEventListener('removetrack', textTrackListChanges);
tracks.addEventListener('addtrack', textTrackListChanges);
this.on('dispose', Fn.bind(this, function () {
tracks.removeEventListener('removetrack', textTrackListChanges);
tracks.removeEventListener('addtrack', textTrackListChanges);
}));
};
/**
* Emulate texttracks
*
* @method emulateTextTracks
*/
Tech.prototype.emulateTextTracks = function emulateTextTracks() {
var _this = this;
var tracks = this.textTracks();
if (!tracks) {
return;
}
if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) {
var script = _globalDocument2['default'].createElement('script');
script.src = this.options_['vtt.js'] || 'https://cdn.rawgit.com/gkatsev/vtt.js/vjs-v0.12.1/dist/vtt.min.js';
this.el().parentNode.appendChild(script);
_globalWindow2['default']['WebVTT'] = true;
}
var updateDisplay = function updateDisplay() {
return _this.trigger('texttrackchange');
};
var textTracksChanges = function textTracksChanges() {
updateDisplay();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeEventListener('cuechange', updateDisplay);
if (track.mode === 'showing') {
track.addEventListener('cuechange', updateDisplay);
}
}
};
textTracksChanges();
tracks.addEventListener('change', textTracksChanges);
this.on('dispose', function () {
tracks.removeEventListener('change', textTracksChanges);
});
};
/*
* Provide default methods for text tracks.
*
* Html5 tech overrides these.
*/
/**
* Get texttracks
*
* @returns {TextTrackList}
* @method textTracks
*/
Tech.prototype.textTracks = function textTracks() {
this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default']();
return this.textTracks_;
};
/**
* Get remote texttracks
*
* @returns {TextTrackList}
* @method remoteTextTracks
*/
Tech.prototype.remoteTextTracks = function remoteTextTracks() {
this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default']();
return this.remoteTextTracks_;
};
/**
* Get remote htmltrackelements
*
* @returns {HTMLTrackElementList}
* @method remoteTextTrackEls
*/
Tech.prototype.remoteTextTrackEls = function remoteTextTrackEls() {
this.remoteTextTrackEls_ = this.remoteTextTrackEls_ || new _tracksHtmlTrackElementList2['default']();
return this.remoteTextTrackEls_;
};
/**
* Creates and returns a remote text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!kind) {
throw new Error('TextTrack kind is required but was not provided');
}
return createTrackHelper(this, kind, label, language);
};
/**
* Creates a remote text track object and returns a emulated html track element
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {HTMLTrackElement}
* @method addRemoteTextTrack
*/
Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
var track = _utilsMergeOptionsJs2['default'](options, {
tech: this
});
var htmlTrackElement = new _tracksHtmlTrackElement2['default'](track);
// store HTMLTrackElement and TextTrack to remote list
this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
this.remoteTextTracks().addTrack_(htmlTrackElement.track);
// must come after remoteTextTracks()
this.textTracks().addTrack_(htmlTrackElement.track);
return htmlTrackElement;
};
/**
* Remove remote texttrack
*
* @param {TextTrackObject} track Texttrack to remove
* @method removeRemoteTextTrack
*/
Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.textTracks().removeTrack_(track);
var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
// remove HTMLTrackElement and TextTrack from remote list
this.remoteTextTrackEls().removeTrackElement_(trackElement);
this.remoteTextTracks().removeTrack_(track);
};
/**
* Provide a default setPoster method for techs
* Poster support for techs should be optional, so we don't want techs to
* break if they don't have a way to set a poster.
*
* @method setPoster
*/
Tech.prototype.setPoster = function setPoster() {};
/*
* Check if the tech can support the given type
*
* The base tech does not support any type, but source handlers might
* overwrite this.
*
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Tech.prototype.canPlayType = function canPlayType() {
return '';
};
/*
* Return whether the argument is a Tech or not.
* Can be passed either a Class like `Html5` or a instance like `player.tech_`
*
* @param {Object} component An item to check
* @return {Boolean} Whether it is a tech or not
*/
Tech.isTech = function isTech(component) {
return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
};
/**
* Registers a Tech
*
* @param {String} name Name of the Tech to register
* @param {Object} tech The tech to register
* @static
* @method registerComponent
*/
Tech.registerTech = function registerTech(name, tech) {
if (!Tech.techs_) {
Tech.techs_ = {};
}
if (!Tech.isTech(tech)) {
throw new Error('Tech ' + name + ' must be a Tech');
}
Tech.techs_[name] = tech;
return tech;
};
/**
* Gets a component by name
*
* @param {String} name Name of the component to get
* @return {Component}
* @static
* @method getComponent
*/
Tech.getTech = function getTech(name) {
if (Tech.techs_ && Tech.techs_[name]) {
return Tech.techs_[name];
}
if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) {
_utilsLogJs2['default'].warn('The ' + name + ' tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)');
return _globalWindow2['default'].videojs[name];
}
};
return Tech;
})(_component2['default']);
Tech.prototype.textTracks_;
var createTrackHelper = function createTrackHelper(self, kind, label, language) {
var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4];
var tracks = self.textTracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.tech = self;
var track = new _tracksTextTrack2['default'](options);
tracks.addTrack_(track);
return track;
};
Tech.prototype.featuresVolumeControl = true;
// Resizing plugins using request fullscreen reloads the plugin
Tech.prototype.featuresFullscreenResize = false;
Tech.prototype.featuresPlaybackRate = false;
// Optional events that we can manually mimic with timers
// currently not triggered by video-js-swf
Tech.prototype.featuresProgressEvents = false;
Tech.prototype.featuresTimeupdateEvents = false;
Tech.prototype.featuresNativeTextTracks = false;
/*
* A functional mixin for techs that want to use the Source Handler pattern.
*
* ##### EXAMPLE:
*
* Tech.withSourceHandlers.call(MyTech);
*
*/
Tech.withSourceHandlers = function (_Tech) {
/*
* Register a source handler
* Source handlers are scripts for handling specific formats.
* The source handler pattern is used for adaptive formats (HLS, DASH) that
* manually load video data and feed it into a Source Buffer (Media Source Extensions)
* @param {Function} handler The source handler
* @param {Boolean} first Register it before any existing handlers
*/
_Tech.registerSourceHandler = function (handler, index) {
var handlers = _Tech.sourceHandlers;
if (!handlers) {
handlers = _Tech.sourceHandlers = [];
}
if (index === undefined) {
// add to the end of the list
index = handlers.length;
}
handlers.splice(index, 0, handler);
};
/*
* Check if the tech can support the given type
* @param {String} type The mimetype to check
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlayType = function (type) {
var handlers = _Tech.sourceHandlers || [];
var can = undefined;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canPlayType(type);
if (can) {
return can;
}
}
return '';
};
/*
* Return the first source handler that supports the source
* TODO: Answer question: should 'probably' be prioritized over 'maybe'
* @param {Object} source The source object
* @returns {Object} The first source handler that supports the source
* @returns {null} Null if no source handler is found
*/
_Tech.selectSourceHandler = function (source) {
var handlers = _Tech.sourceHandlers || [];
var can = undefined;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canHandleSource(source);
if (can) {
return handlers[i];
}
}
return null;
};
/*
* Check if the tech can support the given source
* @param {Object} srcObj The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlaySource = function (srcObj) {
var sh = _Tech.selectSourceHandler(srcObj);
if (sh) {
return sh.canHandleSource(srcObj);
}
return '';
};
/*
* When using a source handler, prefer its implementation of
* any function normally provided by the tech.
*/
var deferrable = ['seekable', 'duration'];
deferrable.forEach(function (fnName) {
var originalFn = this[fnName];
if (typeof originalFn !== 'function') {
return;
}
this[fnName] = function () {
if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
}
return originalFn.apply(this, arguments);
};
}, _Tech.prototype);
/*
* Create a function for setting the source using a source object
* and source handlers.
* Should never be called unless a source handler was found.
* @param {Object} source A source object with src and type keys
* @return {Tech} self
*/
_Tech.prototype.setSource = function (source) {
var sh = _Tech.selectSourceHandler(source);
if (!sh) {
// Fall back to a native source hander when unsupported sources are
// deliberately set
if (_Tech.nativeSourceHandler) {
sh = _Tech.nativeSourceHandler;
} else {
_utilsLogJs2['default'].error('No source hander found for the current source.');
}
}
// Dispose any existing source handler
this.disposeSourceHandler();
this.off('dispose', this.disposeSourceHandler);
this.currentSource_ = source;
this.sourceHandler_ = sh.handleSource(source, this);
this.on('dispose', this.disposeSourceHandler);
return this;
};
/*
* Clean up any existing source handler
*/
_Tech.prototype.disposeSourceHandler = function () {
if (this.sourceHandler_ && this.sourceHandler_.dispose) {
this.sourceHandler_.dispose();
}
};
};
_component2['default'].registerComponent('Tech', Tech);
// Old name for Tech
_component2['default'].registerComponent('MediaTechController', Tech);
Tech.registerTech('Tech', Tech);
exports['default'] = Tech;
module.exports = exports['default'];
},{"../component":65,"../media-error.js":101,"../tracks/html-track-element":117,"../tracks/html-track-element-list":116,"../tracks/text-track":124,"../tracks/text-track-list":122,"../utils/buffer.js":126,"../utils/fn.js":130,"../utils/log.js":133,"../utils/merge-options.js":134,"../utils/time-ranges.js":136,"global/document":1,"global/window":2}],116:[function(_dereq_,module,exports){
/**
* @file html-track-element.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var HtmlTrackElementList = (function () {
function HtmlTrackElementList() {
var trackElements = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
_classCallCheck(this, HtmlTrackElementList);
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['default'].createElement('custom');
for (var prop in HtmlTrackElementList.prototype) {
if (prop !== 'constructor') {
list[prop] = HtmlTrackElementList.prototype[prop];
}
}
}
list.trackElements_ = [];
Object.defineProperty(list, 'length', {
get: function get() {
return this.trackElements_.length;
}
});
for (var i = 0, _length = trackElements.length; i < _length; i++) {
list.addTrackElement_(trackElements[i]);
}
if (browser.IS_IE8) {
return list;
}
}
HtmlTrackElementList.prototype.addTrackElement_ = function addTrackElement_(trackElement) {
this.trackElements_.push(trackElement);
};
HtmlTrackElementList.prototype.getTrackElementByTrack_ = function getTrackElementByTrack_(track) {
var trackElement_ = undefined;
for (var i = 0, _length2 = this.trackElements_.length; i < _length2; i++) {
if (track === this.trackElements_[i].track) {
trackElement_ = this.trackElements_[i];
break;
}
}
return trackElement_;
};
HtmlTrackElementList.prototype.removeTrackElement_ = function removeTrackElement_(trackElement) {
for (var i = 0, _length3 = this.trackElements_.length; i < _length3; i++) {
if (trackElement === this.trackElements_[i]) {
this.trackElements_.splice(i, 1);
break;
}
}
};
return HtmlTrackElementList;
})();
exports['default'] = HtmlTrackElementList;
module.exports = exports['default'];
},{"../utils/browser.js":125,"global/document":1}],117:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _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 _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _tracksTextTrack = _dereq_('../tracks/text-track');
var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack);
var NONE = 0;
var LOADING = 1;
var LOADED = 2;
var ERROR = 3;
/**
* https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement
*
* interface HTMLTrackElement : HTMLElement {
* attribute DOMString kind;
* attribute DOMString src;
* attribute DOMString srclang;
* attribute DOMString label;
* attribute boolean default;
*
* const unsigned short NONE = 0;
* const unsigned short LOADING = 1;
* const unsigned short LOADED = 2;
* const unsigned short ERROR = 3;
* readonly attribute unsigned short readyState;
*
* readonly attribute TextTrack track;
* };
*
* @param {Object} options TextTrack configuration
* @class HTMLTrackElement
*/
var HTMLTrackElement = (function (_EventTarget) {
_inherits(HTMLTrackElement, _EventTarget);
function HTMLTrackElement() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, HTMLTrackElement);
_EventTarget.call(this);
var readyState = undefined,
trackElement = this;
if (browser.IS_IE8) {
trackElement = _globalDocument2['default'].createElement('custom');
for (var prop in HTMLTrackElement.prototype) {
if (prop !== 'constructor') {
trackElement[prop] = HTMLTrackElement.prototype[prop];
}
}
}
var track = new _tracksTextTrack2['default'](options);
trackElement.kind = track.kind;
trackElement.src = track.src;
trackElement.srclang = track.language;
trackElement.label = track.label;
trackElement['default'] = track['default'];
Object.defineProperty(trackElement, 'readyState', {
get: function get() {
return readyState;
}
});
Object.defineProperty(trackElement, 'track', {
get: function get() {
return track;
}
});
readyState = NONE;
track.addEventListener('loadeddata', function () {
readyState = LOADED;
trackElement.trigger({
type: 'load',
target: trackElement
});
});
if (browser.IS_IE8) {
return trackElement;
}
}
return HTMLTrackElement;
})(_eventTarget2['default']);
HTMLTrackElement.prototype.allowedEvents_ = {
load: 'load'
};
HTMLTrackElement.NONE = NONE;
HTMLTrackElement.LOADING = LOADING;
HTMLTrackElement.LOADED = LOADED;
HTMLTrackElement.ERROR = ERROR;
exports['default'] = HTMLTrackElement;
module.exports = exports['default'];
},{"../event-target":97,"../tracks/text-track":124,"../utils/browser.js":125,"global/document":1}],118:[function(_dereq_,module,exports){
/**
* @file text-track-cue-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist
*
* interface TextTrackCueList {
* readonly attribute unsigned long length;
* getter TextTrackCue (unsigned long index);
* TextTrackCue? getCueById(DOMString id);
* };
*/
var TextTrackCueList = function TextTrackCueList(cues) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrackCueList.prototype) {
if (prop !== 'constructor') {
list[prop] = TextTrackCueList.prototype[prop];
}
}
}
TextTrackCueList.prototype.setCues_.call(list, cues);
Object.defineProperty(list, 'length', {
get: function get() {
return this.length_;
}
});
if (browser.IS_IE8) {
return list;
}
};
TextTrackCueList.prototype.setCues_ = function (cues) {
var oldLength = this.length || 0;
var i = 0;
var l = cues.length;
this.cues_ = cues;
this.length_ = cues.length;
var defineProp = function defineProp(i) {
if (!('' + i in this)) {
Object.defineProperty(this, '' + i, {
get: function get() {
return this.cues_[i];
}
});
}
};
if (oldLength < l) {
i = oldLength;
for (; i < l; i++) {
defineProp.call(this, i);
}
}
};
TextTrackCueList.prototype.getCueById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var cue = this[i];
if (cue.id === id) {
result = cue;
break;
}
}
return result;
};
exports['default'] = TextTrackCueList;
module.exports = exports['default'];
},{"../utils/browser.js":125,"global/document":1}],119:[function(_dereq_,module,exports){
/**
* @file text-track-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuItemJs = _dereq_('../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var darkGray = '#222';
var lightGray = '#ccc';
var fontMap = {
monospace: 'monospace',
sansSerif: 'sans-serif',
serif: 'serif',
monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
monospaceSerif: '"Courier New", monospace',
proportionalSansSerif: 'sans-serif',
proportionalSerif: 'serif',
casual: '"Comic Sans MS", Impact, fantasy',
script: '"Monotype Corsiva", cursive',
smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
};
/**
* The component for displaying text track cues
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class TextTrackDisplay
*/
var TextTrackDisplay = (function (_Component) {
_inherits(TextTrackDisplay, _Component);
function TextTrackDisplay(player, options, ready) {
_classCallCheck(this, TextTrackDisplay);
_Component.call(this, player, options, ready);
player.on('loadstart', Fn.bind(this, this.toggleDisplay));
player.on('texttrackchange', Fn.bind(this, this.updateDisplay));
// This used to be called during player init, but was causing an error
// if a track should show by default and the display hadn't loaded yet.
// Should probably be moved to an external track loader when we support
// tracks that don't need a display.
player.ready(Fn.bind(this, function () {
if (player.tech_ && player.tech_['featuresNativeTextTracks']) {
this.hide();
return;
}
player.on('fullscreenchange', Fn.bind(this, this.updateDisplay));
var tracks = this.options_.playerOptions['tracks'] || [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
this.player_.addRemoteTextTrack(track);
}
}));
}
/**
* Add cue HTML to display
*
* @param {Number} color Hex number for color, like #f0e
* @param {Number} opacity Value for opacity,0.0 - 1.0
* @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)'
* @method constructColor
*/
/**
* Toggle display texttracks
*
* @method toggleDisplay
*/
TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() {
if (this.player_.tech_ && this.player_.tech_['featuresNativeTextTracks']) {
this.hide();
} else {
this.show();
}
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-text-track-display'
});
};
/**
* Clear display texttracks
*
* @method clearDisplay
*/
TextTrackDisplay.prototype.clearDisplay = function clearDisplay() {
if (typeof _globalWindow2['default']['WebVTT'] === 'function') {
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_);
}
};
/**
* Update display texttracks
*
* @method updateDisplay
*/
TextTrackDisplay.prototype.updateDisplay = function updateDisplay() {
var tracks = this.player_.textTracks();
this.clearDisplay();
if (!tracks) {
return;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['mode'] === 'showing') {
this.updateForTrack(track);
}
}
};
/**
* Add texttrack to texttrack list
*
* @param {TextTrackObject} track Texttrack object to be added to list
* @method updateForTrack
*/
TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) {
if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) {
return;
}
var overrides = this.player_['textTrackSettings'].getValues();
var cues = [];
for (var _i = 0; _i < track['activeCues'].length; _i++) {
cues.push(track['activeCues'][_i]);
}
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_);
var i = cues.length;
while (i--) {
var cue = cues[i];
if (!cue) {
continue;
}
var cueDiv = cue.displayState;
if (overrides.color) {
cueDiv.firstChild.style.color = overrides.color;
}
if (overrides.textOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
}
if (overrides.backgroundColor) {
cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
}
if (overrides.backgroundOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
}
if (overrides.windowColor) {
if (overrides.windowOpacity) {
tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
} else {
cueDiv.style.backgroundColor = overrides.windowColor;
}
}
if (overrides.edgeStyle) {
if (overrides.edgeStyle === 'dropshadow') {
cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray;
} else if (overrides.edgeStyle === 'raised') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray;
} else if (overrides.edgeStyle === 'depressed') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray;
} else if (overrides.edgeStyle === 'uniform') {
cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray;
}
}
if (overrides.fontPercent && overrides.fontPercent !== 1) {
var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize);
cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
cueDiv.style.height = 'auto';
cueDiv.style.top = 'auto';
cueDiv.style.bottom = '2px';
}
if (overrides.fontFamily && overrides.fontFamily !== 'default') {
if (overrides.fontFamily === 'small-caps') {
cueDiv.firstChild.style.fontVariant = 'small-caps';
} else {
cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
}
}
}
};
return TextTrackDisplay;
})(_component2['default']);
function constructColor(color, opacity) {
return 'rgba(' +
// color looks like "#f0e"
parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')';
}
/**
* Try to update style
* Some style changes will throw an error, particularly in IE8. Those should be noops.
*
* @param {Element} el The element to be styles
* @param {CSSProperty} style The CSS property to be styled
* @param {CSSStyle} rule The actual style to be applied to the property
* @method tryUpdateStyle
*/
function tryUpdateStyle(el, style, rule) {
//
try {
el.style[style] = rule;
} catch (e) {}
}
_component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay);
exports['default'] = TextTrackDisplay;
module.exports = exports['default'];
},{"../component":65,"../menu/menu-button.js":102,"../menu/menu-item.js":103,"../menu/menu.js":104,"../utils/fn.js":130,"global/document":1,"global/window":2}],120:[function(_dereq_,module,exports){
/**
* @file text-track-enums.js
*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
*
* enum TextTrackMode { "disabled", "hidden", "showing" };
*/
'use strict';
exports.__esModule = true;
var TextTrackMode = {
'disabled': 'disabled',
'hidden': 'hidden',
'showing': 'showing'
};
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind
*
* enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" };
*/
var TextTrackKind = {
'subtitles': 'subtitles',
'captions': 'captions',
'descriptions': 'descriptions',
'chapters': 'chapters',
'metadata': 'metadata'
};
exports.TextTrackMode = TextTrackMode;
exports.TextTrackKind = TextTrackKind;
},{}],121:[function(_dereq_,module,exports){
/**
* Utilities for capturing text track state and re-creating tracks
* based on a capture.
*
* @file text-track-list-converter.js
*/
/**
* Examine a single text track and return a JSON-compatible javascript
* object that represents the text track's state.
* @param track {TextTrackObject} the text track to query
* @return {Object} a serializable javascript representation of the
* @private
*/
'use strict';
exports.__esModule = true;
var trackToJson_ = function trackToJson_(track) {
var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) {
if (track[prop]) {
acc[prop] = track[prop];
}
return acc;
}, {
cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
return {
startTime: cue.startTime,
endTime: cue.endTime,
text: cue.text,
id: cue.id
};
})
});
return ret;
};
/**
* Examine a tech and return a JSON-compatible javascript array that
* represents the state of all text tracks currently configured. The
* return array is compatible with `jsonToTextTracks`.
* @param tech {tech} the tech object to query
* @return {Array} a serializable javascript representation of the
* @function textTracksToJson
*/
var textTracksToJson = function textTracksToJson(tech) {
var trackEls = tech.$$('track');
var trackObjs = Array.prototype.map.call(trackEls, function (t) {
return t.track;
});
var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
var json = trackToJson_(trackEl.track);
if (trackEl.src) {
json.src = trackEl.src;
}
return json;
});
return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
return trackObjs.indexOf(track) === -1;
}).map(trackToJson_));
};
/**
* Creates a set of remote text tracks on a tech based on an array of
* javascript text track representations.
* @param json {Array} an array of text track representation objects,
* like those that would be produced by `textTracksToJson`
* @param tech {tech} the tech to create text tracks on
* @function jsonToTextTracks
*/
var jsonToTextTracks = function jsonToTextTracks(json, tech) {
json.forEach(function (track) {
var addedTrack = tech.addRemoteTextTrack(track).track;
if (!track.src && track.cues) {
track.cues.forEach(function (cue) {
return addedTrack.addCue(cue);
});
}
});
return tech.textTracks();
};
exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ };
module.exports = exports['default'];
},{}],122:[function(_dereq_,module,exports){
/**
* @file text-track-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist
*
* interface TextTrackList : EventTarget {
* readonly attribute unsigned long length;
* getter TextTrack (unsigned long index);
* TextTrack? getTrackById(DOMString id);
*
* attribute EventHandler onchange;
* attribute EventHandler onaddtrack;
* attribute EventHandler onremovetrack;
* };
*/
var TextTrackList = function TextTrackList(tracks) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrackList.prototype) {
if (prop !== 'constructor') {
list[prop] = TextTrackList.prototype[prop];
}
}
}
tracks = tracks || [];
list.tracks_ = [];
Object.defineProperty(list, 'length', {
get: function get() {
return this.tracks_.length;
}
});
for (var i = 0; i < tracks.length; i++) {
list.addTrack_(tracks[i]);
}
if (browser.IS_IE8) {
return list;
}
};
TextTrackList.prototype = Object.create(_eventTarget2['default'].prototype);
TextTrackList.prototype.constructor = TextTrackList;
/*
* change - One or more tracks in the track list have been enabled or disabled.
* addtrack - A track has been added to the track list.
* removetrack - A track has been removed from the track list.
*/
TextTrackList.prototype.allowedEvents_ = {
'change': 'change',
'addtrack': 'addtrack',
'removetrack': 'removetrack'
};
// emulate attribute EventHandler support to allow for feature detection
for (var _event in TextTrackList.prototype.allowedEvents_) {
TextTrackList.prototype['on' + _event] = null;
}
/**
* Add TextTrack from TextTrackList
*
* @param {TextTrack} track
* @method addTrack_
* @private
*/
TextTrackList.prototype.addTrack_ = function (track) {
var index = this.tracks_.length;
if (!('' + index in this)) {
Object.defineProperty(this, index, {
get: function get() {
return this.tracks_[index];
}
});
}
track.addEventListener('modechange', Fn.bind(this, function () {
this.trigger('change');
}));
this.tracks_.push(track);
this.trigger({
type: 'addtrack',
track: track
});
};
/**
* Remove TextTrack from TextTrackList
* NOTE: Be mindful of what is passed in as it may be a HTMLTrackElement
*
* @param {TextTrack} rtrack
* @method removeTrack_
* @private
*/
TextTrackList.prototype.removeTrack_ = function (rtrack) {
var track = undefined;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === rtrack) {
track = this[i];
this.tracks_.splice(i, 1);
break;
}
}
if (!track) {
return;
}
this.trigger({
type: 'removetrack',
track: track
});
};
TextTrackList.prototype.getTrackById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var track = this[i];
if (track.id === id) {
result = track;
break;
}
}
return result;
};
exports['default'] = TextTrackList;
module.exports = exports['default'];
},{"../event-target":97,"../utils/browser.js":125,"../utils/fn.js":130,"global/document":1}],123:[function(_dereq_,module,exports){
/**
* @file text-track-settings.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Manipulate settings of texttracks
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class TextTrackSettings
*/
var TextTrackSettings = (function (_Component) {
_inherits(TextTrackSettings, _Component);
function TextTrackSettings(player, options) {
_classCallCheck(this, TextTrackSettings);
_Component.call(this, player, options);
this.hide();
// Grab `persistTextTrackSettings` from the player options if not passed in child options
if (options.persistTextTrackSettings === undefined) {
this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
}
Events.on(this.$('.vjs-done-button'), 'click', Fn.bind(this, function () {
this.saveSettings();
this.hide();
}));
Events.on(this.$('.vjs-default-button'), 'click', Fn.bind(this, function () {
this.$('.vjs-fg-color > select').selectedIndex = 0;
this.$('.vjs-bg-color > select').selectedIndex = 0;
this.$('.window-color > select').selectedIndex = 0;
this.$('.vjs-text-opacity > select').selectedIndex = 0;
this.$('.vjs-bg-opacity > select').selectedIndex = 0;
this.$('.vjs-window-opacity > select').selectedIndex = 0;
this.$('.vjs-edge-style select').selectedIndex = 0;
this.$('.vjs-font-family select').selectedIndex = 0;
this.$('.vjs-font-percent select').selectedIndex = 2;
this.updateDisplay();
}));
Events.on(this.$('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.$('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay));
if (this.options_.persistTextTrackSettings) {
this.restoreSettings();
}
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackSettings.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-caption-settings vjs-modal-overlay',
innerHTML: captionOptionsMenuTemplate()
});
};
/**
* Get texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @return {Object}
* @method getValues
*/
TextTrackSettings.prototype.getValues = function getValues() {
var textEdge = getSelectedOptionValue(this.$('.vjs-edge-style select'));
var fontFamily = getSelectedOptionValue(this.$('.vjs-font-family select'));
var fgColor = getSelectedOptionValue(this.$('.vjs-fg-color > select'));
var textOpacity = getSelectedOptionValue(this.$('.vjs-text-opacity > select'));
var bgColor = getSelectedOptionValue(this.$('.vjs-bg-color > select'));
var bgOpacity = getSelectedOptionValue(this.$('.vjs-bg-opacity > select'));
var windowColor = getSelectedOptionValue(this.$('.window-color > select'));
var windowOpacity = getSelectedOptionValue(this.$('.vjs-window-opacity > select'));
var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(this.$('.vjs-font-percent > select')));
var result = {
'backgroundOpacity': bgOpacity,
'textOpacity': textOpacity,
'windowOpacity': windowOpacity,
'edgeStyle': textEdge,
'fontFamily': fontFamily,
'color': fgColor,
'backgroundColor': bgColor,
'windowColor': windowColor,
'fontPercent': fontPercent
};
for (var _name in result) {
if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) {
delete result[_name];
}
}
return result;
};
/**
* Set texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @param {Object} values Object with texttrack setting values
* @method setValues
*/
TextTrackSettings.prototype.setValues = function setValues(values) {
setSelectedOption(this.$('.vjs-edge-style select'), values.edgeStyle);
setSelectedOption(this.$('.vjs-font-family select'), values.fontFamily);
setSelectedOption(this.$('.vjs-fg-color > select'), values.color);
setSelectedOption(this.$('.vjs-text-opacity > select'), values.textOpacity);
setSelectedOption(this.$('.vjs-bg-color > select'), values.backgroundColor);
setSelectedOption(this.$('.vjs-bg-opacity > select'), values.backgroundOpacity);
setSelectedOption(this.$('.window-color > select'), values.windowColor);
setSelectedOption(this.$('.vjs-window-opacity > select'), values.windowOpacity);
var fontPercent = values.fontPercent;
if (fontPercent) {
fontPercent = fontPercent.toFixed(2);
}
setSelectedOption(this.$('.vjs-font-percent > select'), fontPercent);
};
/**
* Restore texttrack settings
*
* @method restoreSettings
*/
TextTrackSettings.prototype.restoreSettings = function restoreSettings() {
var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings'));
var err = _safeParseTuple[0];
var values = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
if (values) {
this.setValues(values);
}
};
/**
* Save texttrack settings to local storage
*
* @method saveSettings
*/
TextTrackSettings.prototype.saveSettings = function saveSettings() {
if (!this.options_.persistTextTrackSettings) {
return;
}
var values = this.getValues();
try {
if (Object.getOwnPropertyNames(values).length > 0) {
_globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values));
} else {
_globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings');
}
} catch (e) {}
};
/**
* Update display of texttrack settings
*
* @method updateDisplay
*/
TextTrackSettings.prototype.updateDisplay = function updateDisplay() {
var ttDisplay = this.player_.getChild('textTrackDisplay');
if (ttDisplay) {
ttDisplay.updateDisplay();
}
};
return TextTrackSettings;
})(_component2['default']);
_component2['default'].registerComponent('TextTrackSettings', TextTrackSettings);
function getSelectedOptionValue(target) {
var selectedOption = undefined;
// not all browsers support selectedOptions, so, fallback to options
if (target.selectedOptions) {
selectedOption = target.selectedOptions[0];
} else if (target.options) {
selectedOption = target.options[target.options.selectedIndex];
}
return selectedOption.value;
}
function setSelectedOption(target, value) {
if (!value) {
return;
}
var i = undefined;
for (i = 0; i < target.options.length; i++) {
var option = target.options[i];
if (option.value === value) {
break;
}
}
target.selectedIndex = i;
}
function captionOptionsMenuTemplate() {
var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>';
return template;
}
exports['default'] = TextTrackSettings;
module.exports = exports['default'];
},{"../component":65,"../utils/events.js":129,"../utils/fn.js":130,"../utils/log.js":133,"global/window":2,"safe-json-parse/tuple":53}],124:[function(_dereq_,module,exports){
/**
* @file text-track.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _textTrackCueList = _dereq_('./text-track-cue-list');
var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('../utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _textTrackEnums = _dereq_('./text-track-enums');
var TextTrackEnum = _interopRequireWildcard(_textTrackEnums);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsUrlJs = _dereq_('../utils/url.js');
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_xhr);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack
*
* interface TextTrack : EventTarget {
* readonly attribute TextTrackKind kind;
* readonly attribute DOMString label;
* readonly attribute DOMString language;
*
* readonly attribute DOMString id;
* readonly attribute DOMString inBandMetadataTrackDispatchType;
*
* attribute TextTrackMode mode;
*
* readonly attribute TextTrackCueList? cues;
* readonly attribute TextTrackCueList? activeCues;
*
* void addCue(TextTrackCue cue);
* void removeCue(TextTrackCue cue);
*
* attribute EventHandler oncuechange;
* };
*/
var TextTrack = function TextTrack() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!options.tech) {
throw new Error('A tech was not provided.');
}
var tt = this;
if (browser.IS_IE8) {
tt = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrack.prototype) {
if (prop !== 'constructor') {
tt[prop] = TextTrack.prototype[prop];
}
}
}
tt.tech_ = options.tech;
var mode = TextTrackEnum.TextTrackMode[options['mode']] || 'disabled';
var kind = TextTrackEnum.TextTrackKind[options['kind']] || 'subtitles';
var label = options['label'] || '';
var language = options['language'] || options['srclang'] || '';
var id = options['id'] || 'vjs_text_track_' + Guid.newGUID();
if (kind === 'metadata' || kind === 'chapters') {
mode = 'hidden';
}
tt.cues_ = [];
tt.activeCues_ = [];
var cues = new _textTrackCueList2['default'](tt.cues_);
var activeCues = new _textTrackCueList2['default'](tt.activeCues_);
var changed = false;
var timeupdateHandler = Fn.bind(tt, function () {
this['activeCues'];
if (changed) {
this['trigger']('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.tech_.on('timeupdate', timeupdateHandler);
}
Object.defineProperty(tt, 'kind', {
get: function get() {
return kind;
},
set: Function.prototype
});
Object.defineProperty(tt, 'label', {
get: function get() {
return label;
},
set: Function.prototype
});
Object.defineProperty(tt, 'language', {
get: function get() {
return language;
},
set: Function.prototype
});
Object.defineProperty(tt, 'id', {
get: function get() {
return id;
},
set: Function.prototype
});
Object.defineProperty(tt, 'mode', {
get: function get() {
return mode;
},
set: function set(newMode) {
if (!TextTrackEnum.TextTrackMode[newMode]) {
return;
}
mode = newMode;
if (mode === 'showing') {
this.tech_.on('timeupdate', timeupdateHandler);
}
this.trigger('modechange');
}
});
Object.defineProperty(tt, 'cues', {
get: function get() {
if (!this.loaded_) {
return null;
}
return cues;
},
set: Function.prototype
});
Object.defineProperty(tt, 'activeCues', {
get: function get() {
if (!this.loaded_) {
return null;
}
if (this['cues'].length === 0) {
return activeCues; // nothing to do
}
var ct = this.tech_.currentTime();
var active = [];
for (var i = 0, l = this['cues'].length; i < l; i++) {
var cue = this['cues'][i];
if (cue['startTime'] <= ct && cue['endTime'] >= ct) {
active.push(cue);
} else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activeCues_.length) {
changed = true;
} else {
for (var i = 0; i < active.length; i++) {
if (indexOf.call(this.activeCues_, active[i]) === -1) {
changed = true;
}
}
}
this.activeCues_ = active;
activeCues.setCues_(this.activeCues_);
return activeCues;
},
set: Function.prototype
});
if (options.src) {
tt.src = options.src;
loadTrack(options.src, tt);
} else {
tt.loaded_ = true;
}
if (browser.IS_IE8) {
return tt;
}
};
TextTrack.prototype = Object.create(_eventTarget2['default'].prototype);
TextTrack.prototype.constructor = TextTrack;
/*
* cuechange - One or more cues in the track have become active or stopped being active.
*/
TextTrack.prototype.allowedEvents_ = {
'cuechange': 'cuechange'
};
TextTrack.prototype.addCue = function (cue) {
var tracks = this.tech_.textTracks();
if (tracks) {
for (var i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removeCue(cue);
}
}
}
this.cues_.push(cue);
this['cues'].setCues_(this.cues_);
};
TextTrack.prototype.removeCue = function (removeCue) {
var removed = false;
for (var i = 0, l = this.cues_.length; i < l; i++) {
var cue = this.cues_[i];
if (cue === removeCue) {
this.cues_.splice(i, 1);
removed = true;
}
}
if (removed) {
this.cues.setCues_(this.cues_);
}
};
/*
* Downloading stuff happens below this point
*/
var parseCues = function parseCues(srcContent, track) {
var parser = new _globalWindow2['default'].WebVTT.Parser(_globalWindow2['default'], _globalWindow2['default'].vttjs, _globalWindow2['default'].WebVTT.StringDecoder());
parser.oncue = function (cue) {
track.addCue(cue);
};
parser.onparsingerror = function (error) {
_utilsLogJs2['default'].error(error);
};
parser.onflush = function () {
track.trigger({
type: 'loadeddata',
target: track
});
};
parser.parse(srcContent);
parser.flush();
};
var loadTrack = function loadTrack(src, track) {
var opts = {
uri: src
};
var crossOrigin = _utilsUrlJs.isCrossOrigin(src);
if (crossOrigin) {
opts.cors = crossOrigin;
}
_xhr2['default'](opts, Fn.bind(this, function (err, response, responseBody) {
if (err) {
return _utilsLogJs2['default'].error(err, response);
}
track.loaded_ = true;
// NOTE: this is only used for the alt/video.novtt.js build
if (typeof _globalWindow2['default'].WebVTT !== 'function') {
_globalWindow2['default'].setTimeout(function () {
parseCues(responseBody, track);
}, 100);
} else {
parseCues(responseBody, track);
}
}));
};
var indexOf = function indexOf(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
exports['default'] = TextTrack;
module.exports = exports['default'];
},{"../event-target":97,"../utils/browser.js":125,"../utils/fn.js":130,"../utils/guid.js":132,"../utils/log.js":133,"../utils/url.js":138,"./text-track-cue-list":118,"./text-track-enums":120,"global/document":1,"global/window":2,"xhr":55}],125:[function(_dereq_,module,exports){
/**
* @file browser.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var USER_AGENT = _globalWindow2['default'].navigator.userAgent;
var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
/*
* Device is an iPhone
*
* @type {Boolean}
* @constant
* @private
*/
var IS_IPHONE = /iPhone/i.test(USER_AGENT);
exports.IS_IPHONE = IS_IPHONE;
var IS_IPAD = /iPad/i.test(USER_AGENT);
exports.IS_IPAD = IS_IPAD;
var IS_IPOD = /iPod/i.test(USER_AGENT);
exports.IS_IPOD = IS_IPOD;
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
exports.IS_IOS = IS_IOS;
var IOS_VERSION = (function () {
var match = USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) {
return match[1];
}
})();
exports.IOS_VERSION = IOS_VERSION;
var IS_ANDROID = /Android/i.test(USER_AGENT);
exports.IS_ANDROID = IS_ANDROID;
var ANDROID_VERSION = (function () {
// This matches Android Major.Minor.Patch versions
// ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i),
major,
minor;
if (!match) {
return null;
}
major = match[1] && parseFloat(match[1]);
minor = match[2] && parseFloat(match[2]);
if (major && minor) {
return parseFloat(match[1] + '.' + match[2]);
} else if (major) {
return major;
} else {
return null;
}
})();
exports.ANDROID_VERSION = ANDROID_VERSION;
// Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3;
exports.IS_OLD_ANDROID = IS_OLD_ANDROID;
var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
exports.IS_FIREFOX = IS_FIREFOX;
var IS_CHROME = /Chrome/i.test(USER_AGENT);
exports.IS_CHROME = IS_CHROME;
var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT);
exports.IS_IE8 = IS_IE8;
var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch);
exports.TOUCH_ENABLED = TOUCH_ENABLED;
var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style);
exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED;
},{"global/document":1,"global/window":2}],126:[function(_dereq_,module,exports){
/**
* @file buffer.js
*/
'use strict';
exports.__esModule = true;
exports.bufferedPercent = bufferedPercent;
var _timeRangesJs = _dereq_('./time-ranges.js');
/**
* Compute how much your video has been buffered
*
* @param {Object} Buffered object
* @param {Number} Total duration
* @return {Number} Percent buffered of the total duration
* @private
* @function bufferedPercent
*/
function bufferedPercent(buffered, duration) {
var bufferedDuration = 0,
start,
end;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = _timeRangesJs.createTimeRange(0, 0);
}
for (var i = 0; i < buffered.length; i++) {
start = buffered.start(i);
end = buffered.end(i);
// buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedDuration += end - start;
}
return bufferedDuration / duration;
}
},{"./time-ranges.js":136}],127:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
/**
* Object containing the default behaviors for available handler methods.
*
* @private
* @type {Object}
*/
var defaultBehaviors = {
get: function get(obj, key) {
return obj[key];
},
set: function set(obj, key, value) {
obj[key] = value;
return true;
}
};
/**
* Expose private objects publicly using a Proxy to log deprecation warnings.
*
* Browsers that do not support Proxy objects will simply return the `target`
* object, so it can be directly exposed.
*
* @param {Object} target The target object.
* @param {Object} messages Messages to display from a Proxy. Only operations
* with an associated message will be proxied.
* @param {String} [messages.get]
* @param {String} [messages.set]
* @return {Object} A Proxy if supported or the `target` argument.
*/
exports['default'] = function (target) {
var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (typeof Proxy === 'function') {
var _ret = (function () {
var handler = {};
// Build a handler object based on those keys that have both messages
// and default behaviors.
Object.keys(messages).forEach(function (key) {
if (defaultBehaviors.hasOwnProperty(key)) {
handler[key] = function () {
_logJs2['default'].warn(messages[key]);
return defaultBehaviors[key].apply(this, arguments);
};
}
});
return {
v: new Proxy(target, handler)
};
})();
if (typeof _ret === 'object') return _ret.v;
}
return target;
};
module.exports = exports['default'];
},{"./log.js":133}],128:[function(_dereq_,module,exports){
/**
* @file dom.js
*/
'use strict';
exports.__esModule = true;
exports.getEl = getEl;
exports.createEl = createEl;
exports.textContent = textContent;
exports.insertElFirst = insertElFirst;
exports.getElData = getElData;
exports.hasElData = hasElData;
exports.removeElData = removeElData;
exports.hasElClass = hasElClass;
exports.addElClass = addElClass;
exports.removeElClass = removeElClass;
exports.toggleElClass = toggleElClass;
exports.setElAttributes = setElAttributes;
exports.getElAttributes = getElAttributes;
exports.blockTextSelection = blockTextSelection;
exports.unblockTextSelection = unblockTextSelection;
exports.findElPosition = findElPosition;
exports.getPointerPosition = getPointerPosition;
exports.isEl = isEl;
exports.isTextNode = isTextNode;
exports.emptyEl = emptyEl;
exports.normalizeContent = normalizeContent;
exports.appendContent = appendContent;
exports.insertContent = insertContent;
var _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
var _tsml = _dereq_('tsml');
var _tsml2 = _interopRequireDefault(_tsml);
/**
* Detect if a value is a string with any non-whitespace characters.
*
* @param {String} str
* @return {Boolean}
*/
function isNonBlankString(str) {
return typeof str === 'string' && /\S/.test(str);
}
/**
* Throws an error if the passed string has whitespace. This is used by
* class methods to be relatively consistent with the classList API.
*
* @param {String} str
* @return {Boolean}
*/
function throwIfWhitespace(str) {
if (/\s/.test(str)) {
throw new Error('class has illegal whitespace characters');
}
}
/**
* Produce a regular expression for matching a class name.
*
* @param {String} className
* @return {RegExp}
*/
function classRegExp(className) {
return new RegExp('(^|\\s)' + className + '($|\\s)');
}
/**
* Creates functions to query the DOM using a given method.
*
* @function createQuerier
* @private
* @param {String} method
* @return {Function}
*/
function createQuerier(method) {
return function (selector, context) {
if (!isNonBlankString(selector)) {
return _globalDocument2['default'][method](null);
}
if (isNonBlankString(context)) {
context = _globalDocument2['default'].querySelector(context);
}
return (isEl(context) ? context : _globalDocument2['default'])[method](selector);
};
}
/**
* Shorthand for document.getElementById()
* Also allows for CSS (jQuery) ID syntax. But nothing other than IDs.
*
* @param {String} id Element ID
* @return {Element} Element with supplied ID
* @function getEl
*/
function getEl(id) {
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
return _globalDocument2['default'].getElementById(id);
}
/**
* Creates an element and applies properties.
*
* @param {String=} tagName Name of tag to be created.
* @param {Object=} properties Element properties to be applied.
* @return {Element}
* @function createEl
*/
function createEl() {
var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0];
var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var el = _globalDocument2['default'].createElement(tagName);
Object.getOwnPropertyNames(properties).forEach(function (propName) {
var val = properties[propName];
// See #2176
// We originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
_logJs2['default'].warn(_tsml2['default'](_templateObject, propName, val));
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var val = attributes[attrName];
el.setAttribute(attrName, attributes[attrName]);
});
return el;
}
/**
* Injects text into an element, replacing any existing contents entirely.
*
* @param {Element} el
* @param {String} text
* @return {Element}
* @function textContent
*/
function textContent(el, text) {
if (typeof el.textContent === 'undefined') {
el.innerText = text;
} else {
el.textContent = text;
}
}
/**
* Insert an element as the first child node of another
*
* @param {Element} child Element to insert
* @param {Element} parent Element to insert child into
* @private
* @function insertElFirst
*/
function insertElFirst(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
}
/**
* Element Data Store. Allows for binding data to an element without putting it directly on the element.
* Ex. Event listeners are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
*
* @type {Object}
* @private
*/
var elData = {};
/*
* Unique attribute name to store an element's guid in
*
* @type {String}
* @constant
* @private
*/
var elIdAttr = 'vdata' + new Date().getTime();
/**
* Returns the cache object where data for an element is stored
*
* @param {Element} el Element to store data for.
* @return {Object}
* @function getElData
*/
function getElData(el) {
var id = el[elIdAttr];
if (!id) {
id = el[elIdAttr] = Guid.newGUID();
}
if (!elData[id]) {
elData[id] = {};
}
return elData[id];
}
/**
* Returns whether or not an element has cached data
*
* @param {Element} el A dom element
* @return {Boolean}
* @private
* @function hasElData
*/
function hasElData(el) {
var id = el[elIdAttr];
if (!id) {
return false;
}
return !!Object.getOwnPropertyNames(elData[id]).length;
}
/**
* Delete data for the element from the cache and the guid attr from getElementById
*
* @param {Element} el Remove data for an element
* @private
* @function removeElData
*/
function removeElData(el) {
var id = el[elIdAttr];
if (!id) {
return;
}
// Remove all stored data
delete elData[id];
// Remove the elIdAttr property from the DOM node
try {
delete el[elIdAttr];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(elIdAttr);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[elIdAttr] = null;
}
}
}
/**
* Check if an element has a CSS class
*
* @function hasElClass
* @param {Element} element Element to check
* @param {String} classToCheck Classname to check
*/
function hasElClass(element, classToCheck) {
if (element.classList) {
return element.classList.contains(classToCheck);
} else {
throwIfWhitespace(classToCheck);
return classRegExp(classToCheck).test(element.className);
}
}
/**
* Add a CSS class name to an element
*
* @function addElClass
* @param {Element} element Element to add class name to
* @param {String} classToAdd Classname to add
*/
function addElClass(element, classToAdd) {
if (element.classList) {
element.classList.add(classToAdd);
// Don't need to `throwIfWhitespace` here because `hasElClass` will do it
// in the case of classList not being supported.
} else if (!hasElClass(element, classToAdd)) {
element.className = (element.className + ' ' + classToAdd).trim();
}
return element;
}
/**
* Remove a CSS class name from an element
*
* @function removeElClass
* @param {Element} element Element to remove from class name
* @param {String} classToRemove Classname to remove
*/
function removeElClass(element, classToRemove) {
if (element.classList) {
element.classList.remove(classToRemove);
} else {
throwIfWhitespace(classToRemove);
element.className = element.className.split(/\s+/).filter(function (c) {
return c !== classToRemove;
}).join(' ');
}
return element;
}
/**
* Adds or removes a CSS class name on an element depending on an optional
* condition or the presence/absence of the class name.
*
* @function toggleElClass
* @param {Element} element
* @param {String} classToToggle
* @param {Boolean|Function} [predicate]
* Can be a function that returns a Boolean. If `true`, the class
* will be added; if `false`, the class will be removed. If not
* given, the class will be added if not present and vice versa.
*/
function toggleElClass(element, classToToggle, predicate) {
// This CANNOT use `classList` internally because IE does not support the
// second parameter to the `classList.toggle()` method! Which is fine because
// `classList` will be used by the add/remove functions.
var has = hasElClass(element, classToToggle);
if (typeof predicate === 'function') {
predicate = predicate(element, classToToggle);
}
if (typeof predicate !== 'boolean') {
predicate = !has;
}
// If the necessary class operation matches the current state of the
// element, no action is required.
if (predicate === has) {
return;
}
if (predicate) {
addElClass(element, classToToggle);
} else {
removeElClass(element, classToToggle);
}
return element;
}
/**
* Apply attributes to an HTML element.
*
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
* @private
* @function setElAttributes
*/
function setElAttributes(el, attributes) {
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var attrValue = attributes[attrName];
if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, attrValue === true ? '' : attrValue);
}
});
}
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributes are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
*
* @param {Element} tag Element from which to get tag attributes
* @return {Object}
* @private
* @function getElAttributes
*/
function getElAttributes(tag) {
var obj, knownBooleans, attrs, attrName, attrVal;
obj = {};
// known boolean attributes
// we can check for matching boolean properties, but older browsers
// won't know about HTML5 boolean attributes that we still read from
knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ',';
if (tag && tag.attributes && tag.attributes.length > 0) {
attrs = tag.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
attrName = attrs[i].name;
attrVal = attrs[i].value;
// check for known booleans
// the matching element property will return a value for typeof
if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
// the value of an included boolean attribute is typically an empty
// string ('') which would equal false if we just check for a false value.
// we also don't want support bad code like autoplay='false'
attrVal = attrVal !== null ? true : false;
}
obj[attrName] = attrVal;
}
}
return obj;
}
/**
* Attempt to block the ability to select text while dragging controls
*
* @return {Boolean}
* @function blockTextSelection
*/
function blockTextSelection() {
_globalDocument2['default'].body.focus();
_globalDocument2['default'].onselectstart = function () {
return false;
};
}
/**
* Turn off text selection blocking
*
* @return {Boolean}
* @function unblockTextSelection
*/
function unblockTextSelection() {
_globalDocument2['default'].onselectstart = function () {
return true;
};
}
/**
* Offset Left
* getBoundingClientRect technique from
* John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
*
* @function findElPosition
* @param {Element} el Element from which to get offset
* @return {Object}
*/
function findElPosition(el) {
var box = undefined;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
var docEl = _globalDocument2['default'].documentElement;
var body = _globalDocument2['default'].body;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft;
var left = box.left + scrollLeft - clientLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop;
var top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: Math.round(left),
top: Math.round(top)
};
}
/**
* Get pointer position in element
* Returns an object with x and y coordinates.
* The base on the coordinates are the bottom left of the element.
*
* @function getPointerPosition
* @param {Element} el Element on which to get the pointer position on
* @param {Event} event Event object
* @return {Object} This object will have x and y coordinates corresponding to the mouse position
*/
function getPointerPosition(el, event) {
var position = {};
var box = findElPosition(el);
var boxW = el.offsetWidth;
var boxH = el.offsetHeight;
var boxY = box.top;
var boxX = box.left;
var pageY = event.pageY;
var pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
}
/**
* Determines, via duck typing, whether or not a value is a DOM element.
*
* @function isEl
* @param {Mixed} value
* @return {Boolean}
*/
function isEl(value) {
return !!value && typeof value === 'object' && value.nodeType === 1;
}
/**
* Determines, via duck typing, whether or not a value is a text node.
*
* @param {Mixed} value
* @return {Boolean}
*/
function isTextNode(value) {
return !!value && typeof value === 'object' && value.nodeType === 3;
}
/**
* Empties the contents of an element.
*
* @function emptyEl
* @param {Element} el
* @return {Element}
*/
function emptyEl(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
return el;
}
/**
* Normalizes content for eventual insertion into the DOM.
*
* This allows a wide range of content definition methods, but protects
* from falling into the trap of simply writing to `innerHTML`, which is
* an XSS concern.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* - String
* Normalized into a text node.
*
* - Element, TextNode
* Passed through.
*
* - Array
* A one-dimensional array of strings, elements, nodes, or functions (which
* return single strings, elements, or nodes).
*
* - Function
* If the sole argument, is expected to produce a string, element,
* node, or array.
*
* @function normalizeContent
* @param {String|Element|TextNode|Array|Function} content
* @return {Array}
*/
function normalizeContent(content) {
// First, invoke content if it is a function. If it produces an array,
// that needs to happen before normalization.
if (typeof content === 'function') {
content = content();
}
// Next up, normalize to an array, so one or many items can be normalized,
// filtered, and returned.
return (Array.isArray(content) ? content : [content]).map(function (value) {
// First, invoke value if it is a function to produce a new value,
// which will be subsequently normalized to a Node of some kind.
if (typeof value === 'function') {
value = value();
}
if (isEl(value) || isTextNode(value)) {
return value;
}
if (typeof value === 'string' && /\S/.test(value)) {
return _globalDocument2['default'].createTextNode(value);
}
}).filter(function (value) {
return value;
});
}
/**
* Normalizes and appends content to an element.
*
* @function appendContent
* @param {Element} el
* @param {String|Element|TextNode|Array|Function} content
* See: `normalizeContent`
* @return {Element}
*/
function appendContent(el, content) {
normalizeContent(content).forEach(function (node) {
return el.appendChild(node);
});
return el;
}
/**
* Normalizes and inserts content into an element; this is identical to
* `appendContent()`, except it empties the element first.
*
* @function insertContent
* @param {Element} el
* @param {String|Element|TextNode|Array|Function} content
* See: `normalizeContent`
* @return {Element}
*/
function insertContent(el, content) {
return appendContent(emptyEl(el), content);
}
/**
* Finds a single DOM element matching `selector` within the optional
* `context` of another DOM element (defaulting to `document`).
*
* @function $
* @param {String} selector
* A valid CSS selector, which will be passed to `querySelector`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {Element|null}
*/
var $ = createQuerier('querySelector');
exports.$ = $;
/**
* Finds a all DOM elements matching `selector` within the optional
* `context` of another DOM element (defaulting to `document`).
*
* @function $$
* @param {String} selector
* A valid CSS selector, which will be passed to `querySelectorAll`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {NodeList}
*/
var $$ = createQuerier('querySelectorAll');
exports.$$ = $$;
},{"./guid.js":132,"./log.js":133,"global/document":1,"global/window":2,"tsml":54}],129:[function(_dereq_,module,exports){
/**
* @file events.js
*
* Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
* (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
* This should work very similarly to jQuery's events, however it's based off the book version which isn't as
* robust as jquery's, so there's probably some differences.
*/
'use strict';
exports.__esModule = true;
exports.on = on;
exports.off = off;
exports.trigger = trigger;
exports.one = one;
exports.fixEvent = fixEvent;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _domJs = _dereq_('./dom.js');
var Dom = _interopRequireWildcard(_domJs);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
*
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String|Array} type Type of event to bind to.
* @param {Function} fn Event listener.
* @method on
*/
function on(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(on, elem, type, fn);
}
var data = Dom.getElData(elem);
// We need a place to store all our handler data
if (!data.handlers) data.handlers = {};
if (!data.handlers[type]) data.handlers[type] = [];
if (!fn.guid) fn.guid = Guid.newGUID();
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event, hash) {
if (data.disabled) return;
event = fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
// Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
var handlersCopy = handlers.slice(0);
for (var m = 0, n = handlersCopy.length; m < n; m++) {
if (event.isImmediatePropagationStopped()) {
break;
} else {
handlersCopy[m].call(elem, event, hash);
}
}
}
};
}
if (data.handlers[type].length === 1) {
if (elem.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, data.dispatcher);
}
}
}
/**
* Removes event listeners from an element
*
* @param {Element|Object} elem Object to remove listeners from
* @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element.
* @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type.
* @method off
*/
function off(elem, type, fn) {
// Don't want to add a cache object through getElData if not needed
if (!Dom.hasElData(elem)) return;
var data = Dom.getElData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Array.isArray(type)) {
return _handleMultipleEvents(off, elem, type, fn);
}
// Utility function
var removeType = function removeType(t) {
data.handlers[t] = [];
_cleanUpEvents(elem, t);
};
// Are we removing all bound events?
if (!type) {
for (var t in data.handlers) {
removeType(t);
}return;
}
var handlers = data.handlers[type];
// If no handlers exist, nothing to unbind
if (!handlers) return;
// If no listener was provided, remove all listeners for type
if (!fn) {
removeType(type);
return;
}
// We're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
_cleanUpEvents(elem, type);
}
/**
* Trigger an event for an element
*
* @param {Element|Object} elem Element to trigger an event on
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
function trigger(elem, event, hash) {
// Fetches element data and a reference to the parent (for bubbling).
// Don't want to add a data object to cache for every parent,
// so checking hasElData first.
var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {};
var parent = elem.parentNode || elem.ownerDocument;
// type = event.type || event,
// handler;
// If an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = { type: event, target: elem };
}
// Normalizes the event properties.
event = fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event, hash);
}
// Unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the DOM.
if (parent && !event.isPropagationStopped() && event.bubbles === true) {
trigger.call(null, parent, event, hash);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = Dom.getElData(event.target);
// Checks if the target has a default action for this event.
if (event.target[event.type]) {
// Temporarily disables event dispatching on the target as we have already executed the handler.
targetData.disabled = true;
// Executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
}
// Re-enables event dispatching.
targetData.disabled = false;
}
}
// Inform the triggerer if the default was prevented by returning false
return !event.defaultPrevented;
}
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem Element or object to
* @param {String|Array} type Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
function one(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(one, elem, type, fn);
}
var func = function func() {
off(elem, type, func);
fn.apply(this, arguments);
};
// copy the guid to the new function so it can removed using the original function's ID
func.guid = fn.guid = fn.guid || Guid.newGUID();
on(elem, type, func);
}
/**
* Fix a native event to have standard property values
*
* @param {Object} event Event object to fix
* @return {Object}
* @private
* @method fixEvent
*/
function fixEvent(event) {
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Test if fixing up is needed
// Used to check if !event.stopPropagation instead of isPropagationStopped
// But native events return true for stopPropagation, but don't have
// other expected methods like isPropagationStopped. Seems to be a problem
// with the Javascript Ninja code. So we're just overriding all events now.
if (!event || !event.isPropagationStopped) {
var old = event || _globalWindow2['default'].event;
event = {};
// Clone the old object so that we can modify the values event = {};
// IE8 Doesn't like when you mess with native event properties
// Firefox returns false for event.hasOwnProperty('type') and other props
// which makes copying more difficult.
// TODO: Probably best to create a whitelist of event props
for (var key in old) {
// Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
// Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
// and webkitMovementX/Y
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') {
// Chrome 32+ warns if you try to copy deprecated returnValue, but
// we still want to if preventDefault isn't supported (IE8).
if (!(key === 'returnValue' && old.preventDefault)) {
event[key] = old[key];
}
}
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || _globalDocument2['default'];
}
// Handle which other element the event is related to
if (!event.relatedTarget) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Stop the default browser action
event.preventDefault = function () {
if (old.preventDefault) {
old.preventDefault();
}
event.returnValue = false;
old.returnValue = false;
event.defaultPrevented = true;
};
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
old.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
if (old.stopImmediatePropagation) {
old.stopImmediatePropagation();
}
event.isImmediatePropagationStopped = returnTrue;
event.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX != null) {
var doc = _globalDocument2['default'].documentElement,
body = _globalDocument2['default'].body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button != null) {
event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
}
}
// Returns fixed-up instance
return event;
}
/**
* Clean up the listener cache and dispatchers
*
* @param {Element|Object} elem Element to clean up
* @param {String} type Type of event to clean up
* @private
* @method _cleanUpEvents
*/
function _cleanUpEvents(elem, type) {
var data = Dom.getElData(elem);
// Remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type];
// data.handlers[type] = null;
// Setting to null was causing an error with data.handlers
// Remove the meta-handler from the element
if (elem.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, data.dispatcher);
}
}
// Remove the events object if there are no types left
if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
}
// Finally remove the element data if there is no data left
if (Object.getOwnPropertyNames(data).length === 0) {
Dom.removeElData(elem);
}
}
/**
* Loops through an array of event types and calls the requested method for each type.
*
* @param {Function} fn The event method we want to use.
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String} type Type of event to bind to.
* @param {Function} callback Event listener.
* @private
* @function _handleMultipleEvents
*/
function _handleMultipleEvents(fn, elem, types, callback) {
types.forEach(function (type) {
//Call the event method for each one of the types
fn(elem, type, callback);
});
}
},{"./dom.js":128,"./guid.js":132,"global/document":1,"global/window":2}],130:[function(_dereq_,module,exports){
/**
* @file fn.js
*/
'use strict';
exports.__esModule = true;
var _guidJs = _dereq_('./guid.js');
/**
* Bind (a.k.a proxy or Context). A simple method for changing the context of a function
* It also stores a unique id on the function so it can be easily removed from events
*
* @param {*} context The object to bind as scope
* @param {Function} fn The function to be bound to a scope
* @param {Number=} uid An optional unique ID for the function to be set
* @return {Function}
* @private
* @method bind
*/
var bind = function bind(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) {
fn.guid = _guidJs.newGUID();
}
// Create the new function that changes the context
var ret = function ret() {
return fn.apply(context, arguments);
};
// Allow for the ability to individualize this function
// Needed in the case where multiple objects might share the same prototype
// IF both items add an event listener with the same function, then you try to remove just one
// it will remove both because they both have the same guid.
// when using this, you need to use the bind method when you remove the listener as well.
// currently used in text tracks
ret.guid = uid ? uid + '_' + fn.guid : fn.guid;
return ret;
};
exports.bind = bind;
},{"./guid.js":132}],131:[function(_dereq_,module,exports){
/**
* @file format-time.js
*
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
*
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS or M:SS
* @private
* @function formatTime
*/
'use strict';
exports.__esModule = true;
function formatTime(seconds) {
var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1];
return (function () {
seconds = seconds < 0 ? 0 : seconds;
var s = Math.floor(seconds % 60);
var m = Math.floor(seconds / 60 % 60);
var h = Math.floor(seconds / 3600);
var gm = Math.floor(guide / 60 % 60);
var gh = Math.floor(guide / 3600);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
}
// Check if we need to show hours
h = h > 0 || gh > 0 ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = s < 10 ? '0' + s : s;
return h + m + s;
})();
}
exports['default'] = formatTime;
module.exports = exports['default'];
},{}],132:[function(_dereq_,module,exports){
/**
* @file guid.js
*
* Unique ID for an element or function
* @type {Number}
* @private
*/
"use strict";
exports.__esModule = true;
exports.newGUID = newGUID;
var _guid = 1;
/**
* Get the next unique ID
*
* @return {String}
* @function newGUID
*/
function newGUID() {
return _guid++;
}
},{}],133:[function(_dereq_,module,exports){
/**
* @file log.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Log plain debug messages
*/
var log = function log() {
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function () {
_logType('error', arguments);
};
/**
* Log warning messages
*/
log.warn = function () {
_logType('warn', arguments);
};
/**
* Log messages to the console and history based on the type of message
*
* @param {String} type The type of message, or `null` for `log`
* @param {Object} args The args to be passed to the log
* @private
* @method _logType
*/
function _logType(type, args) {
// convert args to an array to get array functions
var argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in log.history
// Was setting these once outside of this function, but containing them
// in the function makes it easier to test cases where console doesn't exist
var noop = function noop() {};
var console = _globalWindow2['default']['console'] || {
'log': noop,
'warn': noop,
'error': noop
};
if (type) {
// add the type to the front of the message
argsArray.unshift(type.toUpperCase() + ':');
} else {
// default to log with no prefix
type = 'log';
}
// add to history
log.history.push(argsArray);
// add console prefix after adding to history
argsArray.unshift('VIDEOJS:');
// call appropriate log function
if (console[type].apply) {
console[type].apply(console, argsArray);
} else {
// ie8 doesn't allow error.apply, but it will just join() the array anyway
console[type](argsArray.join(' '));
}
}
exports['default'] = log;
module.exports = exports['default'];
},{"global/window":2}],134:[function(_dereq_,module,exports){
/**
* @file merge-options.js
*/
'use strict';
exports.__esModule = true;
exports['default'] = mergeOptions;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
function isPlain(obj) {
return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object;
}
/**
* Merge customizer. video.js simply overwrites non-simple objects
* (like arrays) instead of attempting to overlay them.
* @see https://lodash.com/docs#merge
*/
var customizer = function customizer(destination, source) {
// If we're not working with a plain object, copy the value as is
// If source is an array, for instance, it will replace destination
if (!isPlain(source)) {
return source;
}
// If the new value is a plain object but the first object value is not
// we need to create a new object for the first object to merge with.
// This makes it consistent with how merge() works by default
// and also protects from later changes the to first object affecting
// the second object's values.
if (!isPlain(destination)) {
return mergeOptions(source);
}
};
/**
* Merge one or more options objects, recursively merging **only**
* plain object properties. Previously `deepMerge`.
*
* @param {...Object} source One or more objects to merge
* @returns {Object} a new object that is the union of all
* provided objects
* @function mergeOptions
*/
function mergeOptions() {
// contruct the call dynamically to handle the variable number of
// objects to merge
var args = Array.prototype.slice.call(arguments);
// unshift an empty object into the front of the call as the target
// of the merge
args.unshift({});
// customize conflict resolution to match our historical merge behavior
args.push(customizer);
_lodashCompatObjectMerge2['default'].apply(null, args);
// return the mutated result object
return args[0];
}
module.exports = exports['default'];
},{"lodash-compat/object/merge":40}],135:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var createStyleElement = function createStyleElement(className) {
var style = _globalDocument2['default'].createElement('style');
style.className = className;
return style;
};
exports.createStyleElement = createStyleElement;
var setTextContent = function setTextContent(el, content) {
if (el.styleSheet) {
el.styleSheet.cssText = content;
} else {
el.textContent = content;
}
};
exports.setTextContent = setTextContent;
},{"global/document":1}],136:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
exports.createTimeRanges = createTimeRanges;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
/**
* @file time-ranges.js
*
* Should create a fake TimeRange object
* Mimics an HTML5 time range instance, which has functions that
* return the start and end times for a range
* TimeRanges are returned by the buffered() method
*
* @param {(Number|Array)} Start of a single range or an array of ranges
* @param {Number} End of a single range
* @private
* @method createTimeRanges
*/
function createTimeRanges(start, end) {
if (Array.isArray(start)) {
return createTimeRangesObj(start);
} else if (start === undefined || end === undefined) {
return createTimeRangesObj();
}
return createTimeRangesObj([[start, end]]);
}
exports.createTimeRange = createTimeRanges;
function createTimeRangesObj(ranges) {
if (ranges === undefined || ranges.length === 0) {
return {
length: 0,
start: function start() {
throw new Error('This TimeRanges object is empty');
},
end: function end() {
throw new Error('This TimeRanges object is empty');
}
};
}
return {
length: ranges.length,
start: getRange.bind(null, 'start', 0, ranges),
end: getRange.bind(null, 'end', 1, ranges)
};
}
function getRange(fnName, valueIndex, ranges, rangeIndex) {
if (rangeIndex === undefined) {
_logJs2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.');
rangeIndex = 0;
}
rangeCheck(fnName, rangeIndex, ranges.length - 1);
return ranges[rangeIndex][valueIndex];
}
function rangeCheck(fnName, index, maxIndex) {
if (index < 0 || index > maxIndex) {
throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').');
}
}
},{"./log.js":133}],137:[function(_dereq_,module,exports){
/**
* @file to-title-case.js
*
* Uppercase the first letter of a string
*
* @param {String} string String to be uppercased
* @return {String}
* @private
* @method toTitleCase
*/
"use strict";
exports.__esModule = true;
function toTitleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
exports["default"] = toTitleCase;
module.exports = exports["default"];
},{}],138:[function(_dereq_,module,exports){
/**
* @file url.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
var parseUrl = function parseUrl(url) {
var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
// add the url to an anchor and let the browser parse the URL
var a = _globalDocument2['default'].createElement('a');
a.href = url;
// IE8 (and 9?) Fix
// ie8 doesn't parse the URL correctly until the anchor is actually
// added to the body, and an innerHTML is needed to trigger the parsing
var addToBody = a.host === '' && a.protocol !== 'file:';
var div = undefined;
if (addToBody) {
div = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
_globalDocument2['default'].body.appendChild(div);
}
// Copy the specific URL properties to a new object
// This is also needed for IE8 because the anchor loses its
// properties when it's removed from the dom
var details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
}
// IE9 adds the port to the host property unlike everyone else. If
// a port identifier is added for standard ports, strip it.
if (details.protocol === 'http:') {
details.host = details.host.replace(/:80$/, '');
}
if (details.protocol === 'https:') {
details.host = details.host.replace(/:443$/, '');
}
if (addToBody) {
_globalDocument2['default'].body.removeChild(div);
}
return details;
};
exports.parseUrl = parseUrl;
/**
* Get absolute version of relative URL. Used to tell flash correct URL.
* http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
*
* @param {String} url URL to make absolute
* @return {String} Absolute URL
* @private
* @method getAbsoluteURL
*/
var getAbsoluteURL = function getAbsoluteURL(url) {
// Check if absolute URL
if (!url.match(/^https?:\/\//)) {
// Convert to absolute URL. Flash hosted off-site needs an absolute URL.
var div = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '">x</a>';
url = div.firstChild.href;
}
return url;
};
exports.getAbsoluteURL = getAbsoluteURL;
/**
* Returns the extension of the passed file name. It will return an empty string if you pass an invalid path
*
* @param {String} path The fileName path like '/path/to/file.mp4'
* @returns {String} The extension in lower case or an empty string if no extension could be found.
* @method getFileExtension
*/
var getFileExtension = function getFileExtension(path) {
if (typeof path === 'string') {
var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
var pathParts = splitPathRe.exec(path);
if (pathParts) {
return pathParts.pop().toLowerCase();
}
}
return '';
};
exports.getFileExtension = getFileExtension;
/**
* Returns whether the url passed is a cross domain request or not.
*
* @param {String} url The url to check
* @return {Boolean} Whether it is a cross domain request or not
* @method isCrossOrigin
*/
var isCrossOrigin = function isCrossOrigin(url) {
var winLoc = _globalWindow2['default'].location;
var urlInfo = parseUrl(url);
// IE8 protocol relative urls will return ':' for protocol
var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
// Check if url is for another domain/origin
// IE8 doesn't know location.origin, so we won't rely on it here
var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
return crossOrigin;
};
exports.isCrossOrigin = isCrossOrigin;
},{"global/document":1,"global/window":2}],139:[function(_dereq_,module,exports){
/**
* @file video.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _setup = _dereq_('./setup');
var setup = _interopRequireWildcard(_setup);
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _eventTarget = _dereq_('./event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _player = _dereq_('./player');
var _player2 = _interopRequireDefault(_player);
var _pluginsJs = _dereq_('./plugins.js');
var _pluginsJs2 = _interopRequireDefault(_pluginsJs);
var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js');
var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _tracksTextTrackJs = _dereq_('./tracks/text-track.js');
var _tracksTextTrackJs2 = _interopRequireDefault(_tracksTextTrackJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsFormatTimeJs = _dereq_('./utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsUrlJs = _dereq_('./utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _extendJs = _dereq_('./extend.js');
var _extendJs2 = _interopRequireDefault(_extendJs);
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js');
var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs);
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_xhr);
// Include the built-in techs
var _techTechJs = _dereq_('./tech/tech.js');
var _techTechJs2 = _interopRequireDefault(_techTechJs);
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
var _techFlashJs = _dereq_('./tech/flash.js');
var _techFlashJs2 = _interopRequireDefault(_techFlashJs);
// HTML5 Element Shim for IE8
if (typeof HTMLVideoElement === 'undefined') {
_globalDocument2['default'].createElement('video');
_globalDocument2['default'].createElement('audio');
_globalDocument2['default'].createElement('track');
}
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
* The `videojs` function can be used to initialize or retrieve a player.
* ```js
* var myPlayer = videojs('my_video_id');
* ```
*
* @param {String|Element} id Video element or video element ID
* @param {Object=} options Optional options object for config/settings
* @param {Function=} ready Optional ready callback
* @return {Player} A player instance
* @mixes videojs
* @method videojs
*/
var videojs = function videojs(id, options, ready) {
var tag; // Element of ID
// Allow for element or ID to be passed in
// String ID
if (typeof id === 'string') {
// Adjust for jQuery ID syntax
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
// If a player instance has already been created for this ID return it.
if (videojs.getPlayers()[id]) {
// If options or ready funtion are passed, warn
if (options) {
_utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.');
}
if (ready) {
videojs.getPlayers()[id].ready(ready);
}
return videojs.getPlayers()[id];
// Otherwise get element for ID
} else {
tag = Dom.getEl(id);
}
// ID is a media element
} else {
tag = id;
}
// Check for a useable element
if (!tag || !tag.nodeName) {
// re: nodeName, could be a box div also
throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns
}
// Element may have a player attr referring to an already created player instance.
// If not, set up a new player and return the instance.
return tag['player'] || new _player2['default'](tag, options, ready);
};
// Add default styles
var style = Dom.$('.vjs-styles-defaults');
if (!style) {
style = stylesheet.createStyleElement('vjs-styles-defaults');
var head = Dom.$('head');
head.insertBefore(style, head.firstChild);
stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n ');
}
// Run Auto-load players
// You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
setup.autoSetupTimeout(1, videojs);
/*
* Current software version (semver)
*
* @type {String}
*/
videojs.VERSION = '5.4.2';
/**
* The global options object. These are the settings that take effect
* if no overrides are specified when the player is created.
*
* ```js
* videojs.options.autoplay = true
* // -> all players will autoplay by default
* ```
*
* @type {Object}
*/
videojs.options = _player2['default'].prototype.options_;
/**
* Get an object with the currently created players, keyed by player ID
*
* @return {Object} The created players
* @mixes videojs
* @method getPlayers
*/
videojs.getPlayers = function () {
return _player2['default'].players;
};
/**
* For backward compatibility, expose players object.
*
* @deprecated
* @memberOf videojs
* @property {Object|Proxy} players
*/
videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, {
get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead',
set: 'Modification of videojs.players is deprecated'
});
/**
* Get a component class object by name
* ```js
* var VjsButton = videojs.getComponent('Button');
* // Create a new instance of the component
* var myButton = new VjsButton(myPlayer);
* ```
*
* @return {Component} Component identified by name
* @mixes videojs
* @method getComponent
*/
videojs.getComponent = _component2['default'].getComponent;
/**
* Register a component so it can referred to by name
* Used when adding to other
* components, either through addChild
* `component.addChild('myComponent')`
* or through default children options
* `{ children: ['myComponent'] }`.
* ```js
* // Get a component to subclass
* var VjsButton = videojs.getComponent('Button');
* // Subclass the component (see 'extend' doc for more info)
* var MySpecialButton = videojs.extend(VjsButton, {});
* // Register the new component
* VjsButton.registerComponent('MySepcialButton', MySepcialButton);
* // (optionally) add the new component as a default player child
* myPlayer.addChild('MySepcialButton');
* ```
* NOTE: You could also just initialize the component before adding.
* `component.addChild(new MyComponent());`
*
* @param {String} The class name of the component
* @param {Component} The component class
* @return {Component} The newly registered component
* @mixes videojs
* @method registerComponent
*/
videojs.registerComponent = function (name, comp) {
if (_techTechJs2['default'].isTech(comp)) {
_utilsLogJs2['default'].warn('The ' + name + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)');
}
_component2['default'].registerComponent.call(_component2['default'], name, comp);
};
/**
* Get a Tech class object by name
* ```js
* var Html5 = videojs.getTech('Html5');
* // Create a new instance of the component
* var html5 = new Html5(options);
* ```
*
* @return {Tech} Tech identified by name
* @mixes videojs
* @method getComponent
*/
videojs.getTech = _techTechJs2['default'].getTech;
/**
* Register a Tech so it can referred to by name.
* This is used in the tech order for the player.
*
* ```js
* // get the Html5 Tech
* var Html5 = videojs.getTech('Html5');
* var MyTech = videojs.extend(Html5, {});
* // Register the new Tech
* VjsButton.registerTech('Tech', MyTech);
* var player = videojs('myplayer', {
* techOrder: ['myTech', 'html5']
* });
* ```
*
* @param {String} The class name of the tech
* @param {Tech} The tech class
* @return {Tech} The newly registered Tech
* @mixes videojs
* @method registerTech
*/
videojs.registerTech = _techTechJs2['default'].registerTech;
/**
* A suite of browser and device tests
*
* @type {Object}
* @private
*/
videojs.browser = browser;
/**
* Whether or not the browser supports touch events. Included for backward
* compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED`
* instead going forward.
*
* @deprecated
* @type {Boolean}
*/
videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED;
/**
* Subclass an existing class
* Mimics ES6 subclassing with the `extend` keyword
* ```js
* // Create a basic javascript 'class'
* function MyClass(name){
* // Set a property at initialization
* this.myName = name;
* }
* // Create an instance method
* MyClass.prototype.sayMyName = function(){
* alert(this.myName);
* };
* // Subclass the exisitng class and change the name
* // when initializing
* var MySubClass = videojs.extend(MyClass, {
* constructor: function(name) {
* // Call the super class constructor for the subclass
* MyClass.call(this, name)
* }
* });
* // Create an instance of the new sub class
* var myInstance = new MySubClass('John');
* myInstance.sayMyName(); // -> should alert "John"
* ```
*
* @param {Function} The Class to subclass
* @param {Object} An object including instace methods for the new class
* Optionally including a `constructor` function
* @return {Function} The newly created subclass
* @mixes videojs
* @method extend
*/
videojs.extend = _extendJs2['default'];
/**
* Merge two options objects recursively
* Performs a deep merge like lodash.merge but **only merges plain objects**
* (not arrays, elements, anything else)
* Other values will be copied directly from the second object.
* ```js
* var defaultOptions = {
* foo: true,
* bar: {
* a: true,
* b: [1,2,3]
* }
* };
* var newOptions = {
* foo: false,
* bar: {
* b: [4,5,6]
* }
* };
* var result = videojs.mergeOptions(defaultOptions, newOptions);
* // result.foo = false;
* // result.bar.a = true;
* // result.bar.b = [4,5,6];
* ```
*
* @param {Object} defaults The options object whose values will be overriden
* @param {Object} overrides The options object with values to override the first
* @param {Object} etc Any number of additional options objects
*
* @return {Object} a new object with the merged values
* @mixes videojs
* @method mergeOptions
*/
videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default'];
/**
* Change the context (this) of a function
*
* videojs.bind(newContext, function(){
* this === newContext
* });
*
* NOTE: as of v5.0 we require an ES5 shim, so you should use the native
* `function(){}.bind(newContext);` instead of this.
*
* @param {*} context The object to bind as scope
* @param {Function} fn The function to be bound to a scope
* @param {Number=} uid An optional unique ID for the function to be set
* @return {Function}
*/
videojs.bind = Fn.bind;
/**
* Create a Video.js player plugin
* Plugins are only initialized when options for the plugin are included
* in the player options, or the plugin function on the player instance is
* called.
* **See the plugin guide in the docs for a more detailed example**
* ```js
* // Make a plugin that alerts when the player plays
* videojs.plugin('myPlugin', function(myPluginOptions) {
* myPluginOptions = myPluginOptions || {};
*
* var player = this;
* var alertText = myPluginOptions.text || 'Player is playing!'
*
* player.on('play', function(){
* alert(alertText);
* });
* });
* // USAGE EXAMPLES
* // EXAMPLE 1: New player with plugin options, call plugin immediately
* var player1 = videojs('idOne', {
* myPlugin: {
* text: 'Custom text!'
* }
* });
* // Click play
* // --> Should alert 'Custom text!'
* // EXAMPLE 3: New player, initialize plugin later
* var player3 = videojs('idThree');
* // Click play
* // --> NO ALERT
* // Click pause
* // Initialize plugin using the plugin function on the player instance
* player3.myPlugin({
* text: 'Plugin added later!'
* });
* // Click play
* // --> Should alert 'Plugin added later!'
* ```
*
* @param {String} name The plugin name
* @param {Function} fn The plugin function that will be called with options
* @mixes videojs
* @method plugin
*/
videojs.plugin = _pluginsJs2['default'];
/**
* Adding languages so that they're available to all players.
* ```js
* videojs.addLanguage('es', { 'Hello': 'Hola' });
* ```
*
* @param {String} code The language code or dictionary property
* @param {Object} data The data values to be translated
* @return {Object} The resulting language dictionary object
* @mixes videojs
* @method addLanguage
*/
videojs.addLanguage = function (code, data) {
var _merge;
code = ('' + code).toLowerCase();
return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code];
};
/**
* Log debug messages.
*
* @param {...Object} messages One or more messages to log
*/
videojs.log = _utilsLogJs2['default'];
/**
* Creates an emulated TimeRange object.
*
* @param {Number|Array} start Start time in seconds or an array of ranges
* @param {Number} end End time in seconds
* @return {Object} Fake TimeRange object
* @method createTimeRange
*/
videojs.createTimeRange = videojs.createTimeRanges = _utilsTimeRangesJs.createTimeRanges;
/**
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
*
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS or M:SS
* @method formatTime
*/
videojs.formatTime = _utilsFormatTimeJs2['default'];
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
videojs.parseUrl = Url.parseUrl;
/**
* Returns whether the url passed is a cross domain request or not.
*
* @param {String} url The url to check
* @return {Boolean} Whether it is a cross domain request or not
* @method isCrossOrigin
*/
videojs.isCrossOrigin = Url.isCrossOrigin;
/**
* Event target class.
*
* @type {Function}
*/
videojs.EventTarget = _eventTarget2['default'];
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
*
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String|Array} type Type of event to bind to.
* @param {Function} fn Event listener.
* @method on
*/
videojs.on = Events.on;
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem Element or object to
* @param {String|Array} type Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
videojs.one = Events.one;
/**
* Removes event listeners from an element
*
* @param {Element|Object} elem Object to remove listeners from
* @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element.
* @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type.
* @method off
*/
videojs.off = Events.off;
/**
* Trigger an event for an element
*
* @param {Element|Object} elem Element to trigger an event on
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
videojs.trigger = Events.trigger;
/**
* A cross-browser XMLHttpRequest wrapper. Here's a simple example:
*
* videojs.xhr({
* body: someJSONString,
* uri: "/foo",
* headers: {
* "Content-Type": "application/json"
* }
* }, function (err, resp, body) {
* // check resp.statusCode
* });
*
* Check out the [full
* documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md)
* for more options.
*
* @param {Object} options settings for the request.
* @return {XMLHttpRequest|XDomainRequest} the request object.
* @see https://github.com/Raynos/xhr
*/
videojs.xhr = _xhr2['default'];
/**
* TextTrack class
*
* @type {Function}
*/
videojs.TextTrack = _tracksTextTrackJs2['default'];
/**
* Determines, via duck typing, whether or not a value is a DOM element.
*
* @method isEl
* @param {Mixed} value
* @return {Boolean}
*/
videojs.isEl = Dom.isEl;
/**
* Determines, via duck typing, whether or not a value is a text node.
*
* @method isTextNode
* @param {Mixed} value
* @return {Boolean}
*/
videojs.isTextNode = Dom.isTextNode;
/**
* Check if an element has a CSS class
*
* @method hasClass
* @param {Element} element Element to check
* @param {String} classToCheck Classname to check
*/
videojs.hasClass = Dom.hasElClass;
/**
* Add a CSS class name to an element
*
* @method addClass
* @param {Element} element Element to add class name to
* @param {String} classToAdd Classname to add
*/
videojs.addClass = Dom.addElClass;
/**
* Remove a CSS class name from an element
*
* @method removeClass
* @param {Element} element Element to remove from class name
* @param {String} classToRemove Classname to remove
*/
videojs.removeClass = Dom.removeElClass;
/**
* Adds or removes a CSS class name on an element depending on an optional
* condition or the presence/absence of the class name.
*
* @method toggleElClass
* @param {Element} element
* @param {String} classToToggle
* @param {Boolean|Function} [predicate]
* Can be a function that returns a Boolean. If `true`, the class
* will be added; if `false`, the class will be removed. If not
* given, the class will be added if not present and vice versa.
*/
videojs.toggleClass = Dom.toggleElClass;
/**
* Apply attributes to an HTML element.
*
* @method setAttributes
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
*/
videojs.setAttributes = Dom.setElAttributes;
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributes are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
*
* @method getAttributes
* @param {Element} tag Element from which to get tag attributes
* @return {Object}
*/
videojs.getAttributes = Dom.getElAttributes;
/**
* Empties the contents of an element.
*
* @method emptyEl
* @param {Element} el
* @return {Element}
*/
videojs.emptyEl = Dom.emptyEl;
/**
* Normalizes and appends content to an element.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* - String
* Normalized into a text node.
*
* - Element, TextNode
* Passed through.
*
* - Array
* A one-dimensional array of strings, elements, nodes, or functions (which
* return single strings, elements, or nodes).
*
* - Function
* If the sole argument, is expected to produce a string, element,
* node, or array.
*
* @method appendContent
* @param {Element} el
* @param {String|Element|TextNode|Array|Function} content
* @return {Element}
*/
videojs.appendContent = Dom.appendContent;
/**
* Normalizes and inserts content into an element; this is identical to
* `appendContent()`, except it empties the element first.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* - String
* Normalized into a text node.
*
* - Element, TextNode
* Passed through.
*
* - Array
* A one-dimensional array of strings, elements, nodes, or functions (which
* return single strings, elements, or nodes).
*
* - Function
* If the sole argument, is expected to produce a string, element,
* node, or array.
*
* @method insertContent
* @param {Element} el
* @param {String|Element|TextNode|Array|Function} content
* @return {Element}
*/
videojs.insertContent = Dom.insertContent;
/*
* Custom Universal Module Definition (UMD)
*
* Video.js will never be a non-browser lib so we can simplify UMD a bunch and
* still support requirejs and browserify. This also needs to be closure
* compiler compatible, so string keys are used.
*/
if (typeof define === 'function' && define['amd']) {
define('videojs', [], function () {
return videojs;
});
// checking that module is an object too because of umdjs/umd#35
} else if (typeof exports === 'object' && typeof module === 'object') {
module['exports'] = videojs;
}
exports['default'] = videojs;
module.exports = exports['default'];
},{"../../src/js/utils/merge-options.js":134,"./component":65,"./event-target":97,"./extend.js":98,"./player":106,"./plugins.js":107,"./setup":109,"./tech/flash.js":112,"./tech/html5.js":113,"./tech/tech.js":115,"./tracks/text-track.js":124,"./utils/browser.js":125,"./utils/create-deprecation-proxy.js":127,"./utils/dom.js":128,"./utils/events.js":129,"./utils/fn.js":130,"./utils/format-time.js":131,"./utils/log.js":133,"./utils/stylesheet.js":135,"./utils/time-ranges.js":136,"./utils/url.js":138,"global/document":1,"lodash-compat/object/merge":40,"object.assign":45,"xhr":55}]},{},[139])(139)
});
//# sourceMappingURL=video.js.map |
src/React/Widgets/AnnotationEditorWidget/ManyScore/index.js | Kitware/paraviewweb | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactWidgets/AnnotationEditorWidget.mcss';
import CollapsibleWidget from '../../CollapsibleWidget';
import ScoreSelector from '../ScoreSelector';
import BGSelector from '../BackgroundScore';
import SelectionEditorWidget from '../../SelectionEditorWidget';
export default function render(props) {
return (
<div className={style.verticalContainer}>
<section className={style.lineContainer}>
<label className={style.nameLabel}>Name</label>
<input
type="text"
name="name"
className={style.nameInput}
value={props.annotation.name}
onChange={props.onAnnotationChange}
onBlur={props.onAnnotationChange}
/>
</section>
<section className={style.lineContainerCenter}>
<SelectionEditorWidget
className={style.flexItem}
selection={props.annotation.selection}
ranges={props.ranges}
getLegend={props.getLegend}
onChange={props.onSelectionChange}
showUncertainty={props.showUncertainty}
>
{props.annotation.score.map((score, idx, array) => (
<BGSelector
key={`bgscore-${idx}`}
index={idx}
fullHeight={array.length === 1}
color={props.scores[score].color}
/>
))}
</SelectionEditorWidget>
<div
className={style.verticalContainer}
style={{ position: 'relative', zIndex: 0 }}
>
{props.annotation.score.map((score, idx) => (
<ScoreSelector
key={`score-${idx}`}
className={style.flexItem}
score={score}
scores={props.scores}
name={`${idx}`}
onChange={props.onScoreChange}
horizontal
/>
))}
</div>
</section>
<section className={style.lineContainerSpaceBetween}>
<label className={style.label} />
<div>
<label className={style.label}>Weight</label>
<input
className={style.weightInput}
type="number"
value={props.annotation.weight}
min="1"
max="10"
name="weight"
onChange={props.onAnnotationChange}
onBlur={props.onAnnotationChange}
/>
</div>
</section>
<section className={style.lineContainerSpaceBetween}>
<CollapsibleWidget title="Rationale" open={props.rationaleOpen}>
<textarea
className={style.textBox}
name="rationale"
rows="5"
value={props.annotation.rationale}
onChange={props.onAnnotationChange}
onBlur={props.onAnnotationChange}
/>
</CollapsibleWidget>
</section>
</div>
);
}
render.propTypes = {
annotation: PropTypes.object,
scores: PropTypes.array,
ranges: PropTypes.object,
getLegend: PropTypes.func,
rationaleOpen: PropTypes.bool,
showUncertainty: PropTypes.bool,
onSelectionChange: PropTypes.func,
onAnnotationChange: PropTypes.func,
onScoreChange: PropTypes.func,
};
render.defaultProps = {
rationaleOpen: false,
showUncertainty: true,
annotation: undefined,
scores: undefined,
ranges: undefined,
getLegend: undefined,
onSelectionChange: undefined,
onAnnotationChange: undefined,
onScoreChange: undefined,
};
|
packages/core/admin/admin/src/content-manager/components/InjectionZoneList/index.js | wistityhq/strapi | import React from 'react';
import PropTypes from 'prop-types';
import { Box } from '@strapi/design-system/Box';
import { useInjectionZone } from '../../../shared/hooks';
const InjectionZoneList = ({ area, ...props }) => {
const compos = useInjectionZone(area);
if (!compos) {
return null;
}
// TODO
return (
<ul>
{compos.map(compo => {
const component = compo.Component(props);
if (component) {
return (
<Box key={compo.name} padding={3} style={{ textAlign: 'center' }}>
<compo.Component {...props} />
</Box>
);
}
return null;
})}
</ul>
);
};
InjectionZoneList.propTypes = {
area: PropTypes.string.isRequired,
};
export default InjectionZoneList;
|
src/svg-icons/maps/add-location.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsAddLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/>
</SvgIcon>
);
MapsAddLocation = pure(MapsAddLocation);
MapsAddLocation.displayName = 'MapsAddLocation';
export default MapsAddLocation;
|
source/client/components/sub-components/MovieCommentsPanel.js | achobanov/ReactJS-Fundamentals-lab | import React from 'react';
import CommentForm from './CommentsForm';
export default class MovieCommentsPanel extends React.Component {
render() {
console.log('[MovieCommentsPanel]', this.props);
let comments = this.props.comments.map(comment => {
return (
<div key={comment._id} className="comment col-sm-9 list-group-item animated fadeIn">
<div className="media">
<div className="media-body">
<p>{ comment.content }</p>
</div>
</div>
</div>
);
});
return (
<div className="list-group">
<h3 className="col-sm-3">Comments:</h3>
{ comments }
<div className="col-sm-6 col-xs-offset-6 list-group-item animated fadeIn">
<div className="media">
<CommentForm movieId={ this.props.movieId } />
</div>
</div>
</div>
);
}
} |
src/index.js | jlhinson/BCA-Spirit-Store-Client | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
//import { createStore } from 'redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import appState from './store/reducers.js';
import { App } from './app.jsx';
require('./assets/favicon.ico');
//let store = createStore(appState);
let store = createStore(appState, undefined, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
dist/1.11.0/jquery-css-deprecated-dimensions-event-alias.min.js | michael829/jquery-builder | /*! jQuery v1.11.0 -css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-effects/support,-dimensions,-offset,-deprecated,-event-alias | (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 -css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-effects/support,-dimensions,-offset,-deprecated,-event-alias",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=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},V=/^(?: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 W=/^(?:input|select|textarea)$/i,X=/^key/,Y=/^(?:mouse|contextmenu)|click/,Z=/^(?:focusinfocus|focusoutblur)$/,$=/^([^.]*)(?:\.(.+)|)$/;function _(){return!0}function ab(){return!1}function bb(){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=$.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=$.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&&!Z.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,Z.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=Y.test(e)?this.mouseHooks:X.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!==bb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===bb()&&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())?_:ab):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:ab,isPropagationStopped:ab,isImmediatePropagationStopped:ab,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=_,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=_,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=_,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 W.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;W.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"),!W.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=ab;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=ab),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 cb(a){var b=db.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var db="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",eb=/ jQuery\d+="(?:null|\d+)"/g,fb=new RegExp("<(?:"+db+")[\\s/>]","i"),gb=/^\s+/,hb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ib=/<([\w:]+)/,jb=/<tbody/i,kb=/<|&#?\w+;/,lb=/<(?:script|style|link)/i,mb=/checked\s*(?:[^=]|=\s*.checked.)/i,nb=/^$|\/(?:java|ecma)script/i,ob=/^true\/(.*)/,pb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,qb={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>"]},rb=cb(z),sb=rb.appendChild(z.createElement("div"));qb.optgroup=qb.option,qb.tbody=qb.tfoot=qb.colgroup=qb.caption=qb.thead,qb.th=qb.td;function tb(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,tb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function ub(a){V.test(a.type)&&(a.defaultChecked=a.checked)}function vb(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 wb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function xb(a){var b=ob.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function yb(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function zb(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 Ab(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?(wb(b).text=a.text,xb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&V.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)||!fb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(sb.innerHTML=a.outerHTML,sb.removeChild(f=sb.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=tb(f),h=tb(a),g=0;null!=(e=h[g]);++g)d[g]&&Ab(e,d[g]);if(b)if(c)for(h=h||tb(a),d=d||tb(f),g=0;null!=(e=h[g]);g++)zb(e,d[g]);else zb(a,f);return d=tb(f,"script"),d.length>0&&yb(d,!i&&tb(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=cb(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(kb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ib.exec(f)||["",""])[1].toLowerCase(),k=qb[i]||qb._default,h.innerHTML=k[1]+f.replace(hb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&gb.test(f)&&p.push(b.createTextNode(gb.exec(f)[0])),!l.tbody){f="table"!==i||jb.test(f)?"<table>"!==k[1]||jb.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(tb(p,"input"),ub),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=tb(o.appendChild(f),"script"),g&&yb(h),c)){e=0;while(f=h[e++])nb.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 U(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=vb(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=vb(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(tb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&yb(tb(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(tb(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 U(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(eb,""):void 0;if(!("string"!=typeof a||lb.test(a)||!l.htmlSerialize&&fb.test(a)||!l.leadingWhitespace&&gb.test(a)||qb[(ib.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(hb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(tb(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(tb(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&&mb.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(tb(i,"script"),wb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,tb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,xb),j=0;f>j;j++)d=g[j],nb.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(pb,"")));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)}}),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 Bb=/\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(Bb,""):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 Cb,Db,Eb=n.expr.attrHandle,Fb=/^(?:checked|selected)$/i,Gb=l.getSetAttribute,Hb=l.input;n.fn.extend({attr:function(a,b){return U(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)?Db:Cb)),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)?Hb&&Gb||!Fb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(Gb?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}}}}}),Db={set:function(a,b,c){return b===!1?n.removeAttr(a,c):Hb&&Gb||!Fb.test(c)?a.setAttribute(!Gb&&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=Eb[b]||n.find.attr;Eb[b]=Hb&&Gb||!Fb.test(b)?function(a,b,d){var e,f;return d||(f=Eb[b],Eb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,Eb[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),Hb&&Gb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):Cb&&Cb.set(a,b,c)}}),Gb||(Cb={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}},Eb.id=Eb.name=Eb.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:Cb.set},n.attrHooks.contenteditable={set:function(a,b,c){Cb.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 Ib=/^(?:input|select|textarea|button|object)$/i,Jb=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return U(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):Ib.test(a.nodeName)||Jb.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 Kb=/[\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(Kb," "):" ")){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(Kb," "):"")){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(Kb," ").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 Lb=n.now(),Mb=/\?/,Nb=/(,)|(\[|{)|(}|])|"(?:[^"\\\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(Nb,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 Ob,Pb,Qb=/#.*$/,Rb=/([?&])_=[^&]*/,Sb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Tb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ub=/^(?:GET|HEAD)$/,Vb=/^\/\//,Wb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Xb={},Yb={},Zb="*/".concat("*");try{Pb=location.href}catch($b){Pb=z.createElement("a"),Pb.href="",Pb=Pb.href}Ob=Wb.exec(Pb.toLowerCase())||[];function _b(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 ac(a,b,c,d){var e={},f=a===Yb;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 bc(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 cc(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 dc(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:Pb,type:"GET",isLocal:Tb.test(Ob[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Zb,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?bc(bc(a,n.ajaxSettings),b):bc(n.ajaxSettings,a)},ajaxPrefilter:_b(Xb),ajaxTransport:_b(Yb),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=Sb.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||Pb)+"").replace(Qb,"").replace(Vb,Ob[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Wb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===Ob[1]&&c[2]===Ob[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(Ob[3]||("http:"===Ob[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),ac(Xb,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=!Ub.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(Mb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Rb.test(e)?e.replace(Rb,"$1_="+Lb++):e+(Mb.test(e)?"&":"?")+"_="+Lb++)),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]?", "+Zb+"; 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=ac(Yb,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=cc(k,v,c)),u=dc(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()}});var ec=/%20/g,fc=/\[\]$/,gc=/\r?\n/g,hc=/^(?:submit|button|image|reset|file)$/i,ic=/^(?:input|select|textarea|keygen)/i;function jc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||fc.test(a)?d(a,e):jc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)jc(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)jc(c,a[c],b,e);return d.join("&").replace(ec,"+")},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")&&ic.test(this.nodeName)&&!hc.test(a)&&(this.checked||!V.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(gc,"\r\n")}}):{name:b.name,value:c.replace(gc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&nc()||oc()}:nc;var kc=0,lc={},mc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in lc)lc[a](void 0,!0)}),l.cors=!!mc&&"withCredentials"in mc,mc=l.ajax=!!mc,mc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++kc;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 lc[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=lc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function nc(){try{return new a.XMLHttpRequest}catch(b){}}function oc(){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 pc=[],qc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=pc.pop()||n.expando+"_"+Lb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(qc.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&qc.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(qc,"$1"+e):b.jsonp!==!1&&(b.url+=(Mb.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,pc.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 rc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&rc)return rc.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},"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var sc=a.jQuery,tc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=tc),b&&a.jQuery===n&&(a.jQuery=sc),n},typeof b===L&&(a.jQuery=a.$=n),n});
//# sourceMappingURL=jquery.min.map |
ajax/libs/parsley.js/2.3.6/parsley.js | honestree/cdnjs | /*!
* Parsley.js
* Version 2.3.6 - built Wed, Mar 23rd 2016, 10:57 am
* http://parsleyjs.org
* Guillaume Potier - <guillaume@wisembly.com>
* Marc-Andre Lafortune - <petroselinum@marc-andre.ca>
* MIT Licensed
*/
// The source code below is generated by babel as
// Parsley is written in ECMAScript 6
//
var _slice = Array.prototype.slice;
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); } }
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : global.parsley = factory(global.jQuery);
})(this, function ($) {
'use strict';
var globalID = 1;
var pastWarnings = {};
var ParsleyUtils__ParsleyUtils = {
// Parsley DOM-API
// returns object from dom attributes and values
attr: function attr($element, namespace, obj) {
var i;
var attribute;
var attributes;
var regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof obj) obj = {};else {
// Clear all own properties. This won't affect prototype's values
for (i in obj) {
if (obj.hasOwnProperty(i)) delete obj[i];
}
}
if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return obj;
attributes = $element[0].attributes;
for (i = attributes.length; i--;) {
attribute = attributes[i];
if (attribute && attribute.specified && regex.test(attribute.name)) {
obj[this.camelize(attribute.name.slice(namespace.length))] = this.deserializeValue(attribute.value);
}
}
return obj;
},
checkAttr: function checkAttr($element, namespace, _checkAttr) {
return $element.is('[' + namespace + _checkAttr + ']');
},
setAttr: function setAttr($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
generateID: function generateID() {
return '' + globalID++;
},
/** Third party functions **/
// Zepto deserialize function
deserializeValue: function deserializeValue(value) {
var num;
try {
return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value;
} catch (e) {
return value;
}
},
// Zepto camelize function
camelize: function camelize(str) {
return str.replace(/-+(.)?/g, function (match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function dasherize(str) {
return str.replace(/::/g, '/').replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/_/g, '-').toLowerCase();
},
warn: function warn() {
var _window$console;
if (window.console && 'function' === typeof window.console.warn) (_window$console = window.console).warn.apply(_window$console, arguments);
},
warnOnce: function warnOnce(msg) {
if (!pastWarnings[msg]) {
pastWarnings[msg] = true;
this.warn.apply(this, arguments);
}
},
_resetWarnings: function _resetWarnings() {
pastWarnings = {};
},
trimString: function trimString(string) {
return string.replace(/^\s+|\s+$/g, '');
},
namespaceEvents: function namespaceEvents(events, namespace) {
events = this.trimString(events || '').split(/\s+/);
if (!events[0]) return '';
return $.map(events, function (evt) {
return evt + '.' + namespace;
}).join(' ');
},
// Object.create polyfill, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
objectCreate: Object.create || (function () {
var Object = function Object() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}
Object.prototype = prototype;
var result = new Object();
Object.prototype = null;
return result;
};
})()
};
var ParsleyUtils__default = ParsleyUtils__ParsleyUtils;
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
var ParsleyDefaults = {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### Field only
// identifier used to group together inputs (e.g. radio buttons...)
multiple: null,
// identifier (or array of identifiers) used to validate only a select group of inputs
group: null,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'first'|'last'|'none'
focus: 'first',
// event(s) that will trigger validation before first failure. eg: `input`...
trigger: false,
// event(s) that will trigger validation after first failure.
triggerAfterFailure: 'input',
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function classHandler(ParsleyField) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function errorsContainer(ParsleyField) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
var ParsleyAbstract = function ParsleyAbstract() {};
ParsleyAbstract.prototype = {
asyncSupport: true, // Deprecated
actualizeOptions: function actualizeOptions() {
ParsleyUtils__default.attr(this.$element, this.options.namespace, this.domOptions);
if (this.parent && this.parent.actualizeOptions) this.parent.actualizeOptions();
return this;
},
_resetOptions: function _resetOptions(initOptions) {
this.domOptions = ParsleyUtils__default.objectCreate(this.parent.options);
this.options = ParsleyUtils__default.objectCreate(this.domOptions);
// Shallow copy of ownProperties of initOptions:
for (var i in initOptions) {
if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i];
}
this.actualizeOptions();
},
_listeners: null,
// Register a callback for the given event name
// Callback is called with context as the first argument and the `this`
// The context is the current parsley instance, or window.Parsley if global
// A return value of `false` will interrupt the calls
on: function on(name, fn) {
this._listeners = this._listeners || {};
var queue = this._listeners[name] = this._listeners[name] || [];
queue.push(fn);
return this;
},
// Deprecated. Use `on` instead
subscribe: function subscribe(name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
},
// Unregister a callback (or all if none is given) for the given event name
off: function off(name, fn) {
var queue = this._listeners && this._listeners[name];
if (queue) {
if (!fn) {
delete this._listeners[name];
} else {
for (var i = queue.length; i--;) if (queue[i] === fn) queue.splice(i, 1);
}
}
return this;
},
// Deprecated. Use `off`
unsubscribe: function unsubscribe(name, fn) {
$.unsubscribeTo(this, name.toLowerCase());
},
// Trigger an event of the given name
// A return value of `false` interrupts the callback chain
// Returns false if execution was interrupted
trigger: function trigger(name, target, extraArg) {
target = target || this;
var queue = this._listeners && this._listeners[name];
var result;
var parentResult;
if (queue) {
for (var i = queue.length; i--;) {
result = queue[i].call(target, target, extraArg);
if (result === false) return result;
}
}
if (this.parent) {
return this.parent.trigger(name, target, extraArg);
}
return true;
},
// Reset UI
reset: function reset() {
// Field case: just emit a reset event for UI
if ('ParsleyForm' !== this.__class__) {
this._resetUI();
return this._trigger('reset');
}
// Form case: emit a reset event for each field
for (var i = 0; i < this.fields.length; i++) this.fields[i].reset();
this._trigger('reset');
},
// Destroy Parsley instance (+ UI)
destroy: function destroy() {
// Field case: emit destroy event to clean UI and then destroy stored instance
this._destroyUI();
if ('ParsleyForm' !== this.__class__) {
this.$element.removeData('Parsley');
this.$element.removeData('ParsleyFieldMultiple');
this._trigger('destroy');
return;
}
// Form case: destroy all its fields and then destroy stored instance
for (var i = 0; i < this.fields.length; i++) this.fields[i].destroy();
this.$element.removeData('Parsley');
this._trigger('destroy');
},
asyncIsValid: function asyncIsValid(group, force) {
ParsleyUtils__default.warnOnce("asyncIsValid is deprecated; please use whenValid instead");
return this.whenValid({ group: group, force: force });
},
_findRelated: function _findRelated() {
return this.options.multiple ? this.parent.$element.find('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]') : this.$element;
}
};
var requirementConverters = {
string: function string(_string) {
return _string;
},
integer: function integer(string) {
if (isNaN(string)) throw 'Requirement is not an integer: "' + string + '"';
return parseInt(string, 10);
},
number: function number(string) {
if (isNaN(string)) throw 'Requirement is not a number: "' + string + '"';
return parseFloat(string);
},
reference: function reference(string) {
// Unused for now
var result = $(string);
if (result.length === 0) throw 'No such reference: "' + string + '"';
return result;
},
boolean: function boolean(string) {
return string !== 'false';
},
object: function object(string) {
return ParsleyUtils__default.deserializeValue(string);
},
regexp: function regexp(_regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (/^\/.*\/(?:[gimy]*)$/.test(_regexp)) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = _regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
_regexp = _regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
} else {
// Anchor regexp:
_regexp = '^' + _regexp + '$';
}
return new RegExp(_regexp, flags);
}
};
var convertArrayRequirement = function convertArrayRequirement(string, length) {
var m = string.match(/^\s*\[(.*)\]\s*$/);
if (!m) throw 'Requirement is not an array: "' + string + '"';
var values = m[1].split(',').map(ParsleyUtils__default.trimString);
if (values.length !== length) throw 'Requirement has ' + values.length + ' values when ' + length + ' are needed';
return values;
};
var convertRequirement = function convertRequirement(requirementType, string) {
var converter = requirementConverters[requirementType || 'string'];
if (!converter) throw 'Unknown requirement specification: "' + requirementType + '"';
return converter(string);
};
var convertExtraOptionRequirement = function convertExtraOptionRequirement(requirementSpec, string, extraOptionReader) {
var main = null;
var extra = {};
for (var key in requirementSpec) {
if (key) {
var value = extraOptionReader(key);
if ('string' === typeof value) value = convertRequirement(requirementSpec[key], value);
extra[key] = value;
} else {
main = convertRequirement(requirementSpec[key], string);
}
}
return [main, extra];
};
// A Validator needs to implement the methods `validate` and `parseRequirements`
var ParsleyValidator = function ParsleyValidator(spec) {
$.extend(true, this, spec);
};
ParsleyValidator.prototype = {
// Returns `true` iff the given `value` is valid according the given requirements.
validate: function validate(value, requirementFirstArg) {
if (this.fn) {
// Legacy style validator
if (arguments.length > 3) // If more args then value, requirement, instance...
requirementFirstArg = [].slice.call(arguments, 1, -1); // Skip first arg (value) and last (instance), combining the rest
return this.fn.call(this, value, requirementFirstArg);
}
if ($.isArray(value)) {
if (!this.validateMultiple) throw 'Validator `' + this.name + '` does not handle multiple values';
return this.validateMultiple.apply(this, arguments);
} else {
if (this.validateNumber) {
if (isNaN(value)) return false;
arguments[0] = parseFloat(arguments[0]);
return this.validateNumber.apply(this, arguments);
}
if (this.validateString) {
return this.validateString.apply(this, arguments);
}
throw 'Validator `' + this.name + '` only handles multiple values';
}
},
// Parses `requirements` into an array of arguments,
// according to `this.requirementType`
parseRequirements: function parseRequirements(requirements, extraOptionReader) {
if ('string' !== typeof requirements) {
// Assume requirement already parsed
// but make sure we return an array
return $.isArray(requirements) ? requirements : [requirements];
}
var type = this.requirementType;
if ($.isArray(type)) {
var values = convertArrayRequirement(requirements, type.length);
for (var i = 0; i < values.length; i++) values[i] = convertRequirement(type[i], values[i]);
return values;
} else if ($.isPlainObject(type)) {
return convertExtraOptionRequirement(type, requirements, extraOptionReader);
} else {
return [convertRequirement(type, requirements)];
}
},
// Defaults:
requirementType: 'string',
priority: 2
};
var ParsleyValidatorRegistry = function ParsleyValidatorRegistry(validators, catalog) {
this.__class__ = 'ParsleyValidatorRegistry';
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
var typeRegexes = {
email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
// Follow https://www.w3.org/TR/html5/infrastructure.html#floating-point-numbers
number: /^-?(\d*\.)?\d+(e[-+]?\d+)?$/i,
integer: /^-?\d+$/,
digits: /^\d+$/,
alphanum: /^\w+$/i,
url: new RegExp("^" +
// protocol identifier
"(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" + "(?:" +
// IP address exclusion
// private & local networks
// "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks
// "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
// TLD identifier
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' + ")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:/\\S*)?" + "$", 'i')
};
typeRegexes.range = typeRegexes.number;
// See http://stackoverflow.com/a/10454560/8279
var decimalPlaces = function decimalPlaces(num) {
var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) {
return 0;
}
return Math.max(0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0) - (
// Adjust for scientific notation.
match[2] ? +match[2] : 0));
};
ParsleyValidatorRegistry.prototype = {
init: function init(validators, catalog) {
this.catalog = catalog;
// Copy prototype's validators:
this.validators = $.extend({}, this.validators);
for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority);
window.Parsley.trigger('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function setLocale(locale) {
if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function addCatalog(locale, messages, set) {
if ('object' === typeof messages) this.catalog[locale] = messages;
if (true === set) return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function addMessage(locale, name, message) {
if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {};
this.catalog[locale][name] = message;
return this;
},
// Add messages for a given locale
addMessages: function addMessages(locale, nameMessageObject) {
for (var name in nameMessageObject) this.addMessage(locale, name, nameMessageObject[name]);
return this;
},
// Add a new validator
//
// addValidator('custom', {
// requirementType: ['integer', 'integer'],
// validateString: function(value, from, to) {},
// priority: 22,
// messages: {
// en: "Hey, that's no good",
// fr: "Aye aye, pas bon du tout",
// }
// })
//
// Old API was addValidator(name, function, priority)
//
addValidator: function addValidator(name, arg1, arg2) {
if (this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is already defined.');else if (ParsleyDefaults.hasOwnProperty(name)) {
ParsleyUtils__default.warn('"' + name + '" is a restricted keyword and is not a valid validator name.');
return;
}
return this._setValidator.apply(this, arguments);
},
updateValidator: function updateValidator(name, arg1, arg2) {
if (!this.validators[name]) {
ParsleyUtils__default.warn('Validator "' + name + '" is not already defined.');
return this.addValidator.apply(this, arguments);
}
return this._setValidator(this, arguments);
},
removeValidator: function removeValidator(name) {
if (!this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is not defined.');
delete this.validators[name];
return this;
},
_setValidator: function _setValidator(name, validator, priority) {
if ('object' !== typeof validator) {
// Old style validator, with `fn` and `priority`
validator = {
fn: validator,
priority: priority
};
}
if (!validator.validate) {
validator = new ParsleyValidator(validator);
}
this.validators[name] = validator;
for (var locale in validator.messages || {}) this.addMessage(locale, name, validator.messages[locale]);
return this;
},
getErrorMessage: function getErrorMessage(constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name) {
var typeMessages = this.catalog[this.locale][constraint.name] || {};
message = typeMessages[constraint.requirements];
} else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMessage: function formatMessage(string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters) string = this.formatMessage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(/%s/i, parameters) : '';
},
// Here is the Parsley default validators list.
// A validator is an object with the following key values:
// - priority: an integer
// - requirement: 'string' (default), 'integer', 'number', 'regexp' or an Array of these
// - validateString, validateMultiple, validateNumber: functions returning `true`, `false` or a promise
// Alternatively, a validator can be a function that returns such an object
//
validators: {
notblank: {
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 2
},
required: {
validateMultiple: function validateMultiple(values) {
return values.length > 0;
},
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 512
},
type: {
validateString: function validateString(value, type) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$step = _ref.step;
var step = _ref$step === undefined ? '1' : _ref$step;
var _ref$base = _ref.base;
var base = _ref$base === undefined ? 0 : _ref$base;
var regex = typeRegexes[type];
if (!regex) {
throw new Error('validator type `' + type + '` is not supported');
}
if (!regex.test(value)) return false;
if ('number' === type) {
if (!/^any$/i.test(step || '')) {
var nb = Number(value);
var decimals = Math.max(decimalPlaces(step), decimalPlaces(base));
if (decimalPlaces(nb) > decimals) // Value can't have too many decimals
return false;
// Be careful of rounding errors by using integers.
var toInt = function toInt(f) {
return Math.round(f * Math.pow(10, decimals));
};
if ((toInt(nb) - toInt(base)) % toInt(step) != 0) return false;
}
}
return true;
},
requirementType: {
'': 'string',
step: 'string',
base: 'number'
},
priority: 256
},
pattern: {
validateString: function validateString(value, regexp) {
return regexp.test(value);
},
requirementType: 'regexp',
priority: 64
},
minlength: {
validateString: function validateString(value, requirement) {
return value.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxlength: {
validateString: function validateString(value, requirement) {
return value.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
length: {
validateString: function validateString(value, min, max) {
return value.length >= min && value.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
mincheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxcheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
check: {
validateMultiple: function validateMultiple(values, min, max) {
return values.length >= min && values.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
min: {
validateNumber: function validateNumber(value, requirement) {
return value >= requirement;
},
requirementType: 'number',
priority: 30
},
max: {
validateNumber: function validateNumber(value, requirement) {
return value <= requirement;
},
requirementType: 'number',
priority: 30
},
range: {
validateNumber: function validateNumber(value, min, max) {
return value >= min && value <= max;
},
requirementType: ['number', 'number'],
priority: 30
},
equalto: {
validateString: function validateString(value, refOrValue) {
var $reference = $(refOrValue);
if ($reference.length) return value === $reference.val();else return value === refOrValue;
},
priority: 256
}
}
};
var ParsleyUI = {};
var diffResults = function diffResults(newResult, oldResult, deep) {
var added = [];
var kept = [];
for (var i = 0; i < newResult.length; i++) {
var found = false;
for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) {
found = true;
break;
}
if (found) kept.push(newResult[i]);else added.push(newResult[i]);
}
return {
kept: kept,
added: added,
removed: !deep ? diffResults(oldResult, newResult, true).added : []
};
};
ParsleyUI.Form = {
_actualizeTriggers: function _actualizeTriggers() {
var _this = this;
this.$element.on('submit.Parsley', function (evt) {
_this.onSubmitValidate(evt);
});
this.$element.on('click.Parsley', 'input[type="submit"], button[type="submit"]', function (evt) {
_this.onSubmitButton(evt);
});
// UI could be disabled
if (false === this.options.uiEnabled) return;
this.$element.attr('novalidate', '');
},
focus: function focus() {
this._focusedField = null;
if (true === this.validationResult || 'none' === this.options.focus) return null;
for (var i = 0; i < this.fields.length; i++) {
var field = this.fields[i];
if (true !== field.validationResult && field.validationResult.length > 0 && 'undefined' === typeof field.options.noFocus) {
this._focusedField = field.$element;
if ('first' === this.options.focus) break;
}
}
if (null === this._focusedField) return null;
return this._focusedField.focus();
},
_destroyUI: function _destroyUI() {
// Reset all event listeners
this.$element.off('.Parsley');
}
};
ParsleyUI.Field = {
_reflowUI: function _reflowUI() {
this._buildUI();
// If this field doesn't have an active UI don't bother doing something
if (!this._ui) return;
// Diff between two validation results
var diff = diffResults(this.validationResult, this._ui.lastValidationResult);
// Then store current validation result for next reflow
this._ui.lastValidationResult = this.validationResult;
// Handle valid / invalid / none field class
this._manageStatusClass();
// Add, remove, updated errors messages
this._manageErrorsMessages(diff);
// Triggers impl
this._actualizeTriggers();
// If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user
if ((diff.kept.length || diff.added.length) && !this._failedOnce) {
this._failedOnce = true;
this._actualizeTriggers();
}
},
// Returns an array of field's error message(s)
getErrorsMessages: function getErrorsMessages() {
// No error message, field is valid
if (true === this.validationResult) return [];
var messages = [];
for (var i = 0; i < this.validationResult.length; i++) messages.push(this.validationResult[i].errorMessage || this._getErrorMessage(this.validationResult[i].assert));
return messages;
},
// It's a goal of Parsley that this method is no longer required [#1073]
addError: function addError(name) {
var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref2.message;
var assert = _ref2.assert;
var _ref2$updateClass = _ref2.updateClass;
var updateClass = _ref2$updateClass === undefined ? true : _ref2$updateClass;
this._buildUI();
this._addError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
updateError: function updateError(name) {
var _ref3 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref3.message;
var assert = _ref3.assert;
var _ref3$updateClass = _ref3.updateClass;
var updateClass = _ref3$updateClass === undefined ? true : _ref3$updateClass;
this._buildUI();
this._updateError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
removeError: function removeError(name) {
var _ref4 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref4$updateClass = _ref4.updateClass;
var updateClass = _ref4$updateClass === undefined ? true : _ref4$updateClass;
this._buildUI();
this._removeError(name);
// edge case possible here: remove a standard Parsley error that is still failing in this.validationResult
// but highly improbable cuz' manually removing a well Parsley handled error makes no sense.
if (updateClass) this._manageStatusClass();
},
_manageStatusClass: function _manageStatusClass() {
if (this.hasConstraints() && this.needsValidation() && true === this.validationResult) this._successClass();else if (this.validationResult.length > 0) this._errorClass();else this._resetClass();
},
_manageErrorsMessages: function _manageErrorsMessages(diff) {
if ('undefined' !== typeof this.options.errorsMessagesDisabled) return;
// Case where we have errorMessage option that configure an unique field error message, regardless failing validators
if ('undefined' !== typeof this.options.errorMessage) {
if (diff.added.length || diff.kept.length) {
this._insertErrorWrapper();
if (0 === this._ui.$errorsWrapper.find('.parsley-custom-error-message').length) this._ui.$errorsWrapper.append($(this.options.errorTemplate).addClass('parsley-custom-error-message'));
return this._ui.$errorsWrapper.addClass('filled').find('.parsley-custom-error-message').html(this.options.errorMessage);
}
return this._ui.$errorsWrapper.removeClass('filled').find('.parsley-custom-error-message').remove();
}
// Show, hide, update failing constraints messages
for (var i = 0; i < diff.removed.length; i++) this._removeError(diff.removed[i].assert.name);
for (i = 0; i < diff.added.length; i++) this._addError(diff.added[i].assert.name, { message: diff.added[i].errorMessage, assert: diff.added[i].assert });
for (i = 0; i < diff.kept.length; i++) this._updateError(diff.kept[i].assert.name, { message: diff.kept[i].errorMessage, assert: diff.kept[i].assert });
},
_addError: function _addError(name, _ref5) {
var message = _ref5.message;
var assert = _ref5.assert;
this._insertErrorWrapper();
this._ui.$errorsWrapper.addClass('filled').append($(this.options.errorTemplate).addClass('parsley-' + name).html(message || this._getErrorMessage(assert)));
},
_updateError: function _updateError(name, _ref6) {
var message = _ref6.message;
var assert = _ref6.assert;
this._ui.$errorsWrapper.addClass('filled').find('.parsley-' + name).html(message || this._getErrorMessage(assert));
},
_removeError: function _removeError(name) {
this._ui.$errorsWrapper.removeClass('filled').find('.parsley-' + name).remove();
},
_getErrorMessage: function _getErrorMessage(constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof this.options[customConstraintErrorMessage]) return window.Parsley.formatMessage(this.options[customConstraintErrorMessage], constraint.requirements);
return window.Parsley.getErrorMessage(constraint);
},
_buildUI: function _buildUI() {
// UI could be already built or disabled
if (this._ui || false === this.options.uiEnabled) return;
var _ui = {};
// Give field its Parsley id in DOM
this.$element.attr(this.options.namespace + 'id', this.__id__);
/** Generate important UI elements and store them in this **/
// $errorClassHandler is the $element that woul have parsley-error and parsley-success classes
_ui.$errorClassHandler = this._manageClassHandler();
// $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer
_ui.errorsWrapperId = 'parsley-id-' + (this.options.multiple ? 'multiple-' + this.options.multiple : this.__id__);
_ui.$errorsWrapper = $(this.options.errorsWrapper).attr('id', _ui.errorsWrapperId);
// ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly
_ui.lastValidationResult = [];
_ui.validationInformationVisible = false;
// Store it in this for later
this._ui = _ui;
},
// Determine which element will have `parsley-error` and `parsley-success` classes
_manageClassHandler: function _manageClassHandler() {
// An element selector could be passed through DOM with `data-parsley-class-handler=#foo`
if ('string' === typeof this.options.classHandler && $(this.options.classHandler).length) return $(this.options.classHandler);
// Class handled could also be determined by function given in Parsley options
var $handler = this.options.classHandler.call(this, this);
// If this function returned a valid existing DOM element, go for it
if ('undefined' !== typeof $handler && $handler.length) return $handler;
// Otherwise, if simple element (input, texatrea, select...) it will perfectly host the classes
if (!this.options.multiple || this.$element.is('select')) return this.$element;
// But if multiple element (radio, checkbox), that would be their parent
return this.$element.parent();
},
_insertErrorWrapper: function _insertErrorWrapper() {
var $errorsContainer;
// Nothing to do if already inserted
if (0 !== this._ui.$errorsWrapper.parent().length) return this._ui.$errorsWrapper.parent();
if ('string' === typeof this.options.errorsContainer) {
if ($(this.options.errorsContainer).length) return $(this.options.errorsContainer).append(this._ui.$errorsWrapper);else ParsleyUtils__default.warn('The errors container `' + this.options.errorsContainer + '` does not exist in DOM');
} else if ('function' === typeof this.options.errorsContainer) $errorsContainer = this.options.errorsContainer.call(this, this);
if ('undefined' !== typeof $errorsContainer && $errorsContainer.length) return $errorsContainer.append(this._ui.$errorsWrapper);
var $from = this.$element;
if (this.options.multiple) $from = $from.parent();
return $from.after(this._ui.$errorsWrapper);
},
_actualizeTriggers: function _actualizeTriggers() {
var _this2 = this;
var $toBind = this._findRelated();
// Remove Parsley events already bound on this field
$toBind.off('.Parsley');
if (this._failedOnce) $toBind.on(ParsleyUtils__default.namespaceEvents(this.options.triggerAfterFailure, 'Parsley'), function () {
_this2.validate();
});else {
$toBind.on(ParsleyUtils__default.namespaceEvents(this.options.trigger, 'Parsley'), function (event) {
_this2._eventValidate(event);
});
}
},
_eventValidate: function _eventValidate(event) {
// For keyup, keypress, keydown, input... events that could be a little bit obstrusive
// do not validate if val length < min threshold on first validation. Once field have been validated once and info
// about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
if (/key|input/.test(event.type)) if (!(this._ui && this._ui.validationInformationVisible) && this.getValue().length <= this.options.validationThreshold) return;
this.validate();
},
_resetUI: function _resetUI() {
// Reset all event listeners
this._failedOnce = false;
this._actualizeTriggers();
// Nothing to do if UI never initialized for this field
if ('undefined' === typeof this._ui) return;
// Reset all errors' li
this._ui.$errorsWrapper.removeClass('filled').children().remove();
// Reset validation class
this._resetClass();
// Reset validation flags and last validation result
this._ui.lastValidationResult = [];
this._ui.validationInformationVisible = false;
},
_destroyUI: function _destroyUI() {
this._resetUI();
if ('undefined' !== typeof this._ui) this._ui.$errorsWrapper.remove();
delete this._ui;
},
_successClass: function _successClass() {
this._ui.validationInformationVisible = true;
this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass);
},
_errorClass: function _errorClass() {
this._ui.validationInformationVisible = true;
this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass);
},
_resetClass: function _resetClass() {
this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass);
}
};
var ParsleyForm = function ParsleyForm(element, domOptions, options) {
this.__class__ = 'ParsleyForm';
this.__id__ = ParsleyUtils__default.generateID();
this.$element = $(element);
this.domOptions = domOptions;
this.options = options;
this.parent = window.Parsley;
this.fields = [];
this.validationResult = null;
};
var ParsleyForm__statusMapping = { pending: null, resolved: true, rejected: false };
ParsleyForm.prototype = {
onSubmitValidate: function onSubmitValidate(event) {
var _this3 = this;
// This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior
if (true === event.parsley) return;
// If we didn't come here through a submit button, use the first one in the form
var $submitSource = this._$submitSource || this.$element.find('input[type="submit"], button[type="submit"]').first();
this._$submitSource = null;
this.$element.find('.parsley-synthetic-submit-button').prop('disabled', true);
if ($submitSource.is('[formnovalidate]')) return;
var promise = this.whenValidate({ event: event });
if ('resolved' === promise.state() && false !== this._trigger('submit')) {
// All good, let event go through. We make this distinction because browsers
// differ in their handling of `submit` being called from inside a submit event [#1047]
} else {
// Rejected or pending: cancel this submit
event.stopImmediatePropagation();
event.preventDefault();
if ('pending' === promise.state()) promise.done(function () {
_this3._submit($submitSource);
});
}
},
onSubmitButton: function onSubmitButton(event) {
this._$submitSource = $(event.target);
},
// internal
// _submit submits the form, this time without going through the validations.
// Care must be taken to "fake" the actual submit button being clicked.
_submit: function _submit($submitSource) {
if (false === this._trigger('submit')) return;
// Add submit button's data
if ($submitSource) {
var $synthetic = this.$element.find('.parsley-synthetic-submit-button').prop('disabled', false);
if (0 === $synthetic.length) $synthetic = $('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element);
$synthetic.attr({
name: $submitSource.attr('name'),
value: $submitSource.attr('value')
});
}
this.$element.trigger($.extend($.Event('submit'), { parsley: true }));
},
// Performs validation on fields while triggering events.
// @returns `true` if all validations succeeds, `false`
// if a failure is immediately detected, or `null`
// if dependant on a promise.
// Consider using `whenValidate` instead.
validate: function validate(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling validate on a parsley form without passing arguments as an object is deprecated.');
var _arguments = _slice.call(arguments);
var group = _arguments[0];
var force = _arguments[1];
var event = _arguments[2];
options = { group: group, force: force, event: event };
}
return ParsleyForm__statusMapping[this.whenValidate(options).state()];
},
whenValidate: function whenValidate() {
var _this4 = this;
var _ref7 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var group = _ref7.group;
var force = _ref7.force;
var event = _ref7.event;
this.submitEvent = event;
if (event) {
this.submitEvent = $.extend({}, event, { preventDefault: function preventDefault() {
ParsleyUtils__default.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
_this4.validationResult = false;
} });
}
this.validationResult = true;
// fire validate event to eventually modify things before very validation
this._trigger('validate');
// Refresh form DOM options and form's fields that could have changed
this._refreshFields();
var promises = this._withoutReactualizingFormOptions(function () {
return $.map(_this4.fields, function (field) {
return field.whenValidate({ force: force, group: group });
});
});
var promiseBasedOnValidationResult = function promiseBasedOnValidationResult() {
var r = $.Deferred();
if (false === _this4.validationResult) r.reject();
return r.resolve().promise();
};
return $.when.apply($, _toConsumableArray(promises)).done(function () {
_this4._trigger('success');
}).fail(function () {
_this4.validationResult = false;
_this4.focus();
_this4._trigger('error');
}).always(function () {
_this4._trigger('validated');
}).pipe(promiseBasedOnValidationResult, promiseBasedOnValidationResult);
},
// Iterate over refreshed fields, and stop on first failure.
// Returns `true` if all fields are valid, `false` if a failure is detected
// or `null` if the result depends on an unresolved promise.
// Prefer using `whenValid` instead.
isValid: function isValid(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling isValid on a parsley form without passing arguments as an object is deprecated.');
var _arguments2 = _slice.call(arguments);
var group = _arguments2[0];
var force = _arguments2[1];
options = { group: group, force: force };
}
return ParsleyForm__statusMapping[this.whenValid(options).state()];
},
// Iterate over refreshed fields and validate them.
// Returns a promise.
// A validation that immediately fails will interrupt the validations.
whenValid: function whenValid() {
var _this5 = this;
var _ref8 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var group = _ref8.group;
var force = _ref8.force;
this._refreshFields();
var promises = this._withoutReactualizingFormOptions(function () {
return $.map(_this5.fields, function (field) {
return field.whenValid({ group: group, force: force });
});
});
return $.when.apply($, _toConsumableArray(promises));
},
_refreshFields: function _refreshFields() {
return this.actualizeOptions()._bindFields();
},
_bindFields: function _bindFields() {
var _this6 = this;
var oldFields = this.fields;
this.fields = [];
this.fieldsMappedById = {};
this._withoutReactualizingFormOptions(function () {
_this6.$element.find(_this6.options.inputs).not(_this6.options.excluded).each(function (_, element) {
var fieldInstance = new window.Parsley.Factory(element, {}, _this6);
// Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && true !== fieldInstance.options.excluded) if ('undefined' === typeof _this6.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
_this6.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
_this6.fields.push(fieldInstance);
}
});
$(oldFields).not(_this6.fields).each(function (_, field) {
field._trigger('reset');
});
});
return this;
},
// Internal only.
// Looping on a form's fields to do validation or similar
// will trigger reactualizing options on all of them, which
// in turn will reactualize the form's options.
// To avoid calling actualizeOptions so many times on the form
// for nothing, _withoutReactualizingFormOptions temporarily disables
// the method actualizeOptions on this form while `fn` is called.
_withoutReactualizingFormOptions: function _withoutReactualizingFormOptions(fn) {
var oldActualizeOptions = this.actualizeOptions;
this.actualizeOptions = function () {
return this;
};
var result = fn();
this.actualizeOptions = oldActualizeOptions;
return result;
},
// Internal only.
// Shortcut to trigger an event
// Returns true iff event is not interrupted and default not prevented.
_trigger: function _trigger(eventName) {
return this.trigger('form:' + eventName);
}
};
var ConstraintFactory = function ConstraintFactory(parsleyField, name, requirements, priority, isDomConstraint) {
if (!/ParsleyField/.test(parsleyField.__class__)) throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
var validatorSpec = window.Parsley._validatorRegistry.validators[name];
var validator = new ParsleyValidator(validatorSpec);
$.extend(this, {
validator: validator,
name: name,
requirements: requirements,
priority: priority || parsleyField.options[name + 'Priority'] || validator.priority,
isDomConstraint: true === isDomConstraint
});
this._parseRequirements(parsleyField.options);
};
var capitalize = function capitalize(str) {
var cap = str[0].toUpperCase();
return cap + str.slice(1);
};
ConstraintFactory.prototype = {
validate: function validate(value, instance) {
var args = this.requirementList.slice(0); // Make copy
args.unshift(value);
args.push(instance);
return this.validator.validate.apply(this.validator, args);
},
_parseRequirements: function _parseRequirements(options) {
var _this7 = this;
this.requirementList = this.validator.parseRequirements(this.requirements, function (key) {
return options[_this7.name + capitalize(key)];
});
}
};
var ParsleyField = function ParsleyField(field, domOptions, options, parsleyFormInstance) {
this.__class__ = 'ParsleyField';
this.__id__ = ParsleyUtils__default.generateID();
this.$element = $(field);
// Set parent if we have one
if ('undefined' !== typeof parsleyFormInstance) {
this.parent = parsleyFormInstance;
}
this.options = options;
this.domOptions = domOptions;
// Initialize some properties
this.constraints = [];
this.constraintsByName = {};
this.validationResult = [];
// Bind constraints
this._bindConstraints();
};
var parsley_field__statusMapping = { pending: null, resolved: true, rejected: false };
ParsleyField.prototype = {
// # Public API
// Validate field and trigger some events for mainly `ParsleyUI`
// @returns `true`, an array of the validators that failed, or
// `null` if validation is not finished. Prefer using whenValidate
validate: function validate(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling validate on a parsley field without passing arguments as an object is deprecated.');
options = { options: options };
}
var promise = this.whenValidate(options);
if (!promise) // If excluded with `group` option
return true;
switch (promise.state()) {
case 'pending':
return null;
case 'resolved':
return true;
case 'rejected':
return this.validationResult;
}
},
// Validate field and trigger some events for mainly `ParsleyUI`
// @returns a promise that succeeds only when all validations do
// or `undefined` if field is not in the given `group`.
whenValidate: function whenValidate() {
var _this8 = this;
var _ref9 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var force = _ref9.force;
var group = _ref9.group;
// do not validate a field if not the same as given validation group
this.refreshConstraints();
if (group && !this._isInGroup(group)) return;
this.value = this.getValue();
// Field Validate event. `this.value` could be altered for custom needs
this._trigger('validate');
return this.whenValid({ force: force, value: this.value, _refreshed: true }).always(function () {
_this8._reflowUI();
}).done(function () {
_this8._trigger('success');
}).fail(function () {
_this8._trigger('error');
}).always(function () {
_this8._trigger('validated');
});
},
hasConstraints: function hasConstraints() {
return 0 !== this.constraints.length;
},
// An empty optional field does not need validation
needsValidation: function needsValidation(value) {
if ('undefined' === typeof value) value = this.getValue();
// If a field is empty and not required, it is valid
// Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators
if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false;
return true;
},
_isInGroup: function _isInGroup(group) {
if ($.isArray(this.options.group)) return -1 !== $.inArray(group, this.options.group);
return this.options.group === group;
},
// Just validate field. Do not trigger any event.
// Returns `true` iff all constraints pass, `false` if there are failures,
// or `null` if the result can not be determined yet (depends on a promise)
// See also `whenValid`.
isValid: function isValid(options) {
if (arguments.length >= 1 && !$.isPlainObject(options)) {
ParsleyUtils__default.warnOnce('Calling isValid on a parsley field without passing arguments as an object is deprecated.');
var _arguments3 = _slice.call(arguments);
var force = _arguments3[0];
var value = _arguments3[1];
options = { force: force, value: value };
}
var promise = this.whenValid(options);
if (!promise) // Excluded via `group`
return true;
return parsley_field__statusMapping[promise.state()];
},
// Just validate field. Do not trigger any event.
// @returns a promise that succeeds only when all validations do
// or `undefined` if the field is not in the given `group`.
// The argument `force` will force validation of empty fields.
// If a `value` is given, it will be validated instead of the value of the input.
whenValid: function whenValid() {
var _this9 = this;
var _ref10 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref10$force = _ref10.force;
var force = _ref10$force === undefined ? false : _ref10$force;
var value = _ref10.value;
var group = _ref10.group;
var _refreshed = _ref10._refreshed;
// Recompute options and rebind constraints to have latest changes
if (!_refreshed) this.refreshConstraints();
// do not validate a field if not the same as given validation group
if (group && !this._isInGroup(group)) return;
this.validationResult = true;
// A field without constraint is valid
if (!this.hasConstraints()) return $.when();
// Value could be passed as argument, needed to add more power to 'field:validate'
if ('undefined' === typeof value || null === value) value = this.getValue();
if (!this.needsValidation(value) && true !== force) return $.when();
var groupedConstraints = this._getGroupedConstraints();
var promises = [];
$.each(groupedConstraints, function (_, constraints) {
// Process one group of constraints at a time, we validate the constraints
// and combine the promises together.
var promise = $.when.apply($, _toConsumableArray($.map(constraints, function (constraint) {
return _this9._validateConstraint(value, constraint);
})));
promises.push(promise);
if (promise.state() === 'rejected') return false; // Interrupt processing if a group has already failed
});
return $.when.apply($, promises);
},
// @returns a promise
_validateConstraint: function _validateConstraint(value, constraint) {
var _this10 = this;
var result = constraint.validate(value, this);
// Map false to a failed promise
if (false === result) result = $.Deferred().reject();
// Make sure we return a promise and that we record failures
return $.when(result).fail(function (errorMessage) {
if (true === _this10.validationResult) _this10.validationResult = [];
_this10.validationResult.push({
assert: constraint,
errorMessage: 'string' === typeof errorMessage && errorMessage
});
});
},
// @returns Parsley field computed value that could be overrided or configured in DOM
getValue: function getValue() {
var value;
// Value could be overriden in DOM or with explicit options
if ('function' === typeof this.options.value) value = this.options.value(this);else if ('undefined' !== typeof this.options.value) value = this.options.value;else value = this.$element.val();
// Handle wrong DOM or configurations
if ('undefined' === typeof value || null === value) return '';
return this._handleWhitespace(value);
},
// Actualize options that could have change since previous validation
// Re-bind accordingly constraints (could be some new, removed or updated)
refreshConstraints: function refreshConstraints() {
return this.actualizeOptions()._bindConstraints();
},
/**
* Add a new constraint to a field
*
* @param {String} name
* @param {Mixed} requirements optional
* @param {Number} priority optional
* @param {Boolean} isDomConstraint optional
*/
addConstraint: function addConstraint(name, requirements, priority, isDomConstraint) {
if (window.Parsley._validatorRegistry.validators[name]) {
var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint);
// if constraint already exist, delete it and push new version
if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name);
this.constraints.push(constraint);
this.constraintsByName[constraint.name] = constraint;
}
return this;
},
// Remove a constraint
removeConstraint: function removeConstraint(name) {
for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) {
this.constraints.splice(i, 1);
break;
}
delete this.constraintsByName[name];
return this;
},
// Update a constraint (Remove + re-add)
updateConstraint: function updateConstraint(name, parameters, priority) {
return this.removeConstraint(name).addConstraint(name, parameters, priority);
},
// # Internals
// Internal only.
// Bind constraints from config + options + DOM
_bindConstraints: function _bindConstraints() {
var constraints = [];
var constraintsByName = {};
// clean all existing DOM constraints to only keep javascript user constraints
for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) {
constraints.push(this.constraints[i]);
constraintsByName[this.constraints[i].name] = this.constraints[i];
}
this.constraints = constraints;
this.constraintsByName = constraintsByName;
// then re-add Parsley DOM-API constraints
for (var name in this.options) this.addConstraint(name, this.options[name], undefined, true);
// finally, bind special HTML5 constraints
return this._bindHtml5Constraints();
},
// Internal only.
// Bind specific HTML5 constraints to be HTML5 compliant
_bindHtml5Constraints: function _bindHtml5Constraints() {
// html5 required
if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true);
// html5 pattern
if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true);
// range
if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true);
// HTML5 min
else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true);
// HTML5 max
else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true);
// length
if ('undefined' !== typeof this.$element.attr('minlength') && 'undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('length', [this.$element.attr('minlength'), this.$element.attr('maxlength')], undefined, true);
// HTML5 minlength
else if ('undefined' !== typeof this.$element.attr('minlength')) this.addConstraint('minlength', this.$element.attr('minlength'), undefined, true);
// HTML5 maxlength
else if ('undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('maxlength', this.$element.attr('maxlength'), undefined, true);
// html5 types
var type = this.$element.attr('type');
if ('undefined' === typeof type) return this;
// Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise
if ('number' === type) {
return this.addConstraint('type', ['number', {
step: this.$element.attr('step'),
base: this.$element.attr('min') || this.$element.attr('value')
}], undefined, true);
// Regular other HTML5 supported types
} else if (/^(email|url|range)$/i.test(type)) {
return this.addConstraint('type', type, undefined, true);
}
return this;
},
// Internal only.
// Field is required if have required constraint without `false` value
_isRequired: function _isRequired() {
if ('undefined' === typeof this.constraintsByName.required) return false;
return false !== this.constraintsByName.required.requirements;
},
// Internal only.
// Shortcut to trigger an event
_trigger: function _trigger(eventName) {
return this.trigger('field:' + eventName);
},
// Internal only
// Handles whitespace in a value
// Use `data-parsley-whitespace="squish"` to auto squish input value
// Use `data-parsley-whitespace="trim"` to auto trim input value
_handleWhitespace: function _handleWhitespace(value) {
if (true === this.options.trimValue) ParsleyUtils__default.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"');
if ('squish' === this.options.whitespace) value = value.replace(/\s{2,}/g, ' ');
if ('trim' === this.options.whitespace || 'squish' === this.options.whitespace || true === this.options.trimValue) value = ParsleyUtils__default.trimString(value);
return value;
},
// Internal only.
// Returns the constraints, grouped by descending priority.
// The result is thus an array of arrays of constraints.
_getGroupedConstraints: function _getGroupedConstraints() {
if (false === this.options.priorityEnabled) return [this.constraints];
var groupedConstraints = [];
var index = {};
// Create array unique of priorities
for (var i = 0; i < this.constraints.length; i++) {
var p = this.constraints[i].priority;
if (!index[p]) groupedConstraints.push(index[p] = []);
index[p].push(this.constraints[i]);
}
// Sort them by priority DESC
groupedConstraints.sort(function (a, b) {
return b[0].priority - a[0].priority;
});
return groupedConstraints;
}
};
var parsley_field = ParsleyField;
var ParsleyMultiple = function ParsleyMultiple() {
this.__class__ = 'ParsleyFieldMultiple';
};
ParsleyMultiple.prototype = {
// Add new `$element` sibling for multiple field
addElement: function addElement($element) {
this.$elements.push($element);
return this;
},
// See `ParsleyField.refreshConstraints()`
refreshConstraints: function refreshConstraints() {
var fieldConstraints;
this.constraints = [];
// Select multiple special treatment
if (this.$element.is('select')) {
this.actualizeOptions()._bindConstraints();
return this;
}
// Gather all constraints for each input in the multiple group
for (var i = 0; i < this.$elements.length; i++) {
// Check if element have not been dynamically removed since last binding
if (!$('html').has(this.$elements[i]).length) {
this.$elements.splice(i, 1);
continue;
}
fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints;
for (var j = 0; j < fieldConstraints.length; j++) this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint);
}
return this;
},
// See `ParsleyField.getValue()`
getValue: function getValue() {
// Value could be overriden in DOM
if ('function' === typeof this.options.value) return this.options.value(this);else if ('undefined' !== typeof this.options.value) return this.options.value;
// Radio input case
if (this.$element.is('input[type=radio]')) return this._findRelated().filter(':checked').val() || '';
// checkbox input case
if (this.$element.is('input[type=checkbox]')) {
var values = [];
this._findRelated().filter(':checked').each(function () {
values.push($(this).val());
});
return values;
}
// Select multiple case
if (this.$element.is('select') && null === this.$element.val()) return [];
// Default case that should never happen
return this.$element.val();
},
_init: function _init() {
this.$elements = [this.$element];
return this;
}
};
var ParsleyFactory = function ParsleyFactory(element, options, parsleyFormInstance) {
this.$element = $(element);
// If the element has already been bound, returns its saved Parsley instance
var savedparsleyFormInstance = this.$element.data('Parsley');
if (savedparsleyFormInstance) {
// If the saved instance has been bound without a ParsleyForm parent and there is one given in this call, add it
if ('undefined' !== typeof parsleyFormInstance && savedparsleyFormInstance.parent === window.Parsley) {
savedparsleyFormInstance.parent = parsleyFormInstance;
savedparsleyFormInstance._resetOptions(savedparsleyFormInstance.options);
}
return savedparsleyFormInstance;
}
// Parsley must be instantiated with a DOM element or jQuery $element
if (!this.$element.length) throw new Error('You must bind Parsley on an existing element.');
if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance');
this.parent = parsleyFormInstance || window.Parsley;
return this.init(options);
};
ParsleyFactory.prototype = {
init: function init(options) {
this.__class__ = 'Parsley';
this.__version__ = '2.3.6';
this.__id__ = ParsleyUtils__default.generateID();
// Pre-compute options
this._resetOptions(options);
// A ParsleyForm instance is obviously a `<form>` element but also every node that is not an input and has the `data-parsley-validate` attribute
if (this.$element.is('form') || ParsleyUtils__default.checkAttr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)) return this.bind('parsleyForm');
// Every other element is bound as a `ParsleyField` or `ParsleyFieldMultiple`
return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField');
},
isMultiple: function isMultiple() {
return this.$element.is('input[type=radio], input[type=checkbox]') || this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple');
},
// Multiples fields are a real nightmare :(
// Maybe some refactoring would be appreciated here...
handleMultiple: function handleMultiple() {
var _this11 = this;
var name;
var multiple;
var parsleyMultipleInstance;
// Handle multiple name
if (this.options.multiple) ; // We already have our 'multiple' identifier
else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) this.options.multiple = name = this.$element.attr('name');else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) this.options.multiple = this.$element.attr('id');
// Special select multiple input
if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) {
this.options.multiple = this.options.multiple || this.__id__;
return this.bind('parsleyFieldMultiple');
// Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it
} else if (!this.options.multiple) {
ParsleyUtils__default.warn('To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element);
return this;
}
// Remove special chars
this.options.multiple = this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, '');
// Add proper `data-parsley-multiple` to siblings if we have a valid multiple name
if ('undefined' !== typeof name) {
$('input[name="' + name + '"]').each(function (i, input) {
if ($(input).is('input[type=radio], input[type=checkbox]')) $(input).attr(_this11.options.namespace + 'multiple', _this11.options.multiple);
});
}
// Check here if we don't already have a related multiple instance saved
var $previouslyRelated = this._findRelated();
for (var i = 0; i < $previouslyRelated.length; i++) {
parsleyMultipleInstance = $($previouslyRelated.get(i)).data('Parsley');
if ('undefined' !== typeof parsleyMultipleInstance) {
if (!this.$element.data('ParsleyFieldMultiple')) {
parsleyMultipleInstance.addElement(this.$element);
}
break;
}
}
// Create a secret ParsleyField instance for every multiple field. It will be stored in `data('ParsleyFieldMultiple')`
// And will be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance
this.bind('parsleyField', true);
return parsleyMultipleInstance || this.bind('parsleyFieldMultiple');
},
// Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple`
bind: function bind(type, doNotStore) {
var parsleyInstance;
switch (type) {
case 'parsleyForm':
parsleyInstance = $.extend(new ParsleyForm(this.$element, this.domOptions, this.options), window.ParsleyExtend)._bindFields();
break;
case 'parsleyField':
parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), window.ParsleyExtend);
break;
case 'parsleyFieldMultiple':
parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), new ParsleyMultiple(), window.ParsleyExtend)._init();
break;
default:
throw new Error(type + 'is not a supported Parsley type');
}
if (this.options.multiple) ParsleyUtils__default.setAttr(this.$element, this.options.namespace, 'multiple', this.options.multiple);
if ('undefined' !== typeof doNotStore) {
this.$element.data('ParsleyFieldMultiple', parsleyInstance);
return parsleyInstance;
}
// Store the freshly bound instance in a DOM element for later access using jQuery `data()`
this.$element.data('Parsley', parsleyInstance);
// Tell the world we have a new ParsleyForm or ParsleyField instance!
parsleyInstance._actualizeTriggers();
parsleyInstance._trigger('init');
return parsleyInstance;
}
};
var vernums = $.fn.jquery.split('.');
if (parseInt(vernums[0]) <= 1 && parseInt(vernums[1]) < 8) {
throw "The loaded version of jQuery is too old. Please upgrade to 1.8.x or better.";
}
if (!vernums.forEach) {
ParsleyUtils__default.warn('Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim');
}
// Inherit `on`, `off` & `trigger` to Parsley:
var Parsley = $.extend(new ParsleyAbstract(), {
$element: $(document),
actualizeOptions: null,
_resetOptions: null,
Factory: ParsleyFactory,
version: '2.3.6'
});
// Supplement ParsleyField and Form with ParsleyAbstract
// This way, the constructors will have access to those methods
$.extend(parsley_field.prototype, ParsleyUI.Field, ParsleyAbstract.prototype);
$.extend(ParsleyForm.prototype, ParsleyUI.Form, ParsleyAbstract.prototype);
// Inherit actualizeOptions and _resetOptions:
$.extend(ParsleyFactory.prototype, ParsleyAbstract.prototype);
// ### jQuery API
// `$('.elem').parsley(options)` or `$('.elem').psly(options)`
$.fn.parsley = $.fn.psly = function (options) {
if (this.length > 1) {
var instances = [];
this.each(function () {
instances.push($(this).parsley(options));
});
return instances;
}
// Return undefined if applied to non existing DOM element
if (!$(this).length) {
ParsleyUtils__default.warn('You must bind Parsley on an existing element.');
return;
}
return new ParsleyFactory(this, options);
};
// ### ParsleyField and ParsleyForm extension
// Ensure the extension is now defined if it wasn't previously
if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {};
// ### Parsley config
// Inherit from ParsleyDefault, and copy over any existing values
Parsley.options = $.extend(ParsleyUtils__default.objectCreate(ParsleyDefaults), window.ParsleyConfig);
window.ParsleyConfig = Parsley.options; // Old way of accessing global options
// ### Globals
window.Parsley = window.psly = Parsley;
window.ParsleyUtils = ParsleyUtils__default;
// ### Define methods that forward to the registry, and deprecate all access except through window.Parsley
var registry = window.Parsley._validatorRegistry = new ParsleyValidatorRegistry(window.ParsleyConfig.validators, window.ParsleyConfig.i18n);
window.ParsleyValidator = {};
$.each('setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator'.split(' '), function (i, method) {
window.Parsley[method] = $.proxy(registry, method);
window.ParsleyValidator[method] = function () {
var _window$Parsley;
ParsleyUtils__default.warnOnce('Accessing the method \'' + method + '\' through ParsleyValidator is deprecated. Simply call \'window.Parsley.' + method + '(...)\'');
return (_window$Parsley = window.Parsley)[method].apply(_window$Parsley, arguments);
};
});
// ### ParsleyUI
// Deprecated global object
window.Parsley.UI = ParsleyUI;
window.ParsleyUI = {
removeError: function removeError(instance, name, doNotUpdateClass) {
var updateClass = true !== doNotUpdateClass;
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'removeError\' on the instance directly. Please comment in issue 1073 as to your need to call this method.');
return instance.removeError(name, { updateClass: updateClass });
},
getErrorsMessages: function getErrorsMessages(instance) {
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'getErrorsMessages\' on the instance directly.');
return instance.getErrorsMessages();
}
};
$.each('addError updateError'.split(' '), function (i, method) {
window.ParsleyUI[method] = function (instance, name, message, assert, doNotUpdateClass) {
var updateClass = true !== doNotUpdateClass;
ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'' + method + '\' on the instance directly. Please comment in issue 1073 as to your need to call this method.');
return instance[method](name, { message: message, assert: assert, updateClass: updateClass });
};
});
// Alleviate glaring Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1250521
// See also https://github.com/guillaumepotier/Parsley.js/issues/1068
if (/firefox/i.test(navigator.userAgent)) {
$(document).on('change', 'select', function (evt) {
$(evt.target).trigger('input');
});
}
// ### PARSLEY auto-binding
// Prevent it by setting `ParsleyConfig.autoBind` to `false`
if (false !== window.ParsleyConfig.autoBind) {
$(function () {
// Works only on `data-parsley-validate`.
if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley();
});
}
var o = $({});
var deprecated = function deprecated() {
ParsleyUtils__default.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley");
};
// Returns an event handler that calls `fn` with the arguments it expects
function adapt(fn, context) {
// Store to allow unbinding
if (!fn.parsleyAdaptedCallback) {
fn.parsleyAdaptedCallback = function () {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(this);
fn.apply(context || o, args);
};
}
return fn.parsleyAdaptedCallback;
}
var eventPrefix = 'parsley:';
// Converts 'parsley:form:validate' into 'form:validate'
function eventName(name) {
if (name.lastIndexOf(eventPrefix, 0) === 0) return name.substr(eventPrefix.length);
return name;
}
// $.listen is deprecated. Use Parsley.on instead.
$.listen = function (name, callback) {
var context;
deprecated();
if ('object' === typeof arguments[1] && 'function' === typeof arguments[2]) {
context = arguments[1];
callback = arguments[2];
}
if ('function' !== typeof callback) throw new Error('Wrong parameters');
window.Parsley.on(eventName(name), adapt(callback, context));
};
$.listenTo = function (instance, name, fn) {
deprecated();
if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance');
if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong parameters');
instance.on(eventName(name), adapt(fn));
};
$.unsubscribe = function (name, fn) {
deprecated();
if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong arguments');
window.Parsley.off(eventName(name), fn.parsleyAdaptedCallback);
};
$.unsubscribeTo = function (instance, name) {
deprecated();
if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance');
instance.off(eventName(name));
};
$.unsubscribeAll = function (name) {
deprecated();
window.Parsley.off(eventName(name));
$('form,input,textarea,select').each(function () {
var instance = $(this).data('Parsley');
if (instance) {
instance.off(eventName(name));
}
});
};
// $.emit is deprecated. Use jQuery events instead.
$.emit = function (name, instance) {
var _instance;
deprecated();
var instanceGiven = instance instanceof parsley_field || instance instanceof ParsleyForm;
var args = Array.prototype.slice.call(arguments, instanceGiven ? 2 : 1);
args.unshift(eventName(name));
if (!instanceGiven) {
instance = window.Parsley;
}
(_instance = instance).trigger.apply(_instance, _toConsumableArray(args));
};
var pubsub = {};
$.extend(true, Parsley, {
asyncValidators: {
'default': {
fn: function fn(xhr) {
// By default, only status 2xx are deemed successful.
// Note: we use status instead of state() because responses with status 200
// but invalid messages (e.g. an empty body for content type set to JSON) will
// result in state() === 'rejected'.
return xhr.status >= 200 && xhr.status < 300;
},
url: false
},
reverse: {
fn: function fn(xhr) {
// If reverse option is set, a failing ajax request is considered successful
return xhr.status < 200 || xhr.status >= 300;
},
url: false
}
},
addAsyncValidator: function addAsyncValidator(name, fn, url, options) {
Parsley.asyncValidators[name] = {
fn: fn,
url: url || false,
options: options || {}
};
return this;
}
});
Parsley.addValidator('remote', {
requirementType: {
'': 'string',
'validator': 'string',
'reverse': 'boolean',
'options': 'object'
},
validateString: function validateString(value, url, options, instance) {
var data = {};
var ajaxOptions;
var csr;
var validator = options.validator || (true === options.reverse ? 'reverse' : 'default');
if ('undefined' === typeof Parsley.asyncValidators[validator]) throw new Error('Calling an undefined async validator: `' + validator + '`');
url = Parsley.asyncValidators[validator].url || url;
// Fill current value
if (url.indexOf('{value}') > -1) {
url = url.replace('{value}', encodeURIComponent(value));
} else {
data[instance.$element.attr('name') || instance.$element.attr('id')] = value;
}
// Merge options passed in from the function with the ones in the attribute
var remoteOptions = $.extend(true, options.options || {}, Parsley.asyncValidators[validator].options);
// All `$.ajax(options)` could be overridden or extended directly from DOM in `data-parsley-remote-options`
ajaxOptions = $.extend(true, {}, {
url: url,
data: data,
type: 'GET'
}, remoteOptions);
// Generate store key based on ajax options
instance.trigger('field:ajaxoptions', instance, ajaxOptions);
csr = $.param(ajaxOptions);
// Initialise querry cache
if ('undefined' === typeof Parsley._remoteCache) Parsley._remoteCache = {};
// Try to retrieve stored xhr
var xhr = Parsley._remoteCache[csr] = Parsley._remoteCache[csr] || $.ajax(ajaxOptions);
var handleXhr = function handleXhr() {
var result = Parsley.asyncValidators[validator].fn.call(instance, xhr, url, options);
if (!result) // Map falsy results to rejected promise
result = $.Deferred().reject();
return $.when(result);
};
return xhr.then(handleXhr, handleXhr);
},
priority: -1
});
Parsley.on('form:submit', function () {
Parsley._remoteCache = {};
});
window.ParsleyExtend.addAsyncValidator = function () {
ParsleyUtils.warnOnce('Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`');
return Parsley.addAsyncValidator.apply(Parsley, arguments);
};
// This is included with the Parsley library itself,
// thus there is no use in adding it to your project.
Parsley.addMessages('en', {
defaultMessage: "This value seems to be invalid.",
type: {
email: "This value should be a valid email.",
url: "This value should be a valid url.",
number: "This value should be a valid number.",
integer: "This value should be a valid integer.",
digits: "This value should be digits.",
alphanum: "This value should be alphanumeric."
},
notblank: "This value should not be blank.",
required: "This value is required.",
pattern: "This value seems to be invalid.",
min: "This value should be greater than or equal to %s.",
max: "This value should be lower than or equal to %s.",
range: "This value should be between %s and %s.",
minlength: "This value is too short. It should have %s characters or more.",
maxlength: "This value is too long. It should have %s characters or fewer.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "You must select at least %s choices.",
maxcheck: "You must select %s choices or fewer.",
check: "You must select between %s and %s choices.",
equalto: "This value should be the same."
});
Parsley.setLocale('en');
var parsley = Parsley;
return parsley;
});
//# sourceMappingURL=parsley.js.map
|
ajax/libs/react/0.11.2/react.js | luanlmd/cdnjs | /**
* React v0.11.2
*/
!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.React=e()}}(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);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}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-2014 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 AutoFocusMixin
* @typechecks static-only
*/
"use strict";
var focusNode = _dereq_("./focusNode");
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
},{"./focusNode":106}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 BeforeInputEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var SyntheticInputEvent = _dereq_("./SyntheticInputEvent");
var keyOf = _dereq_("./keyOf");
var canUseTextInputEvent = (
ExecutionEnvironment.canUseDOM &&
'TextEvent' in window &&
!('documentMode' in document || isPresto())
);
/**
* 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
]
}
};
// Track characters inserted via keypress and composition events.
var fallbackChars = null;
/**
* 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)
);
}
/**
* 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.
*/
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) {
var chars;
if (canUseTextInputEvent) {
switch (topLevelType) {
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;
}
chars = String.fromCharCode(which);
break;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately.
if (chars === SPACEBAR_CHAR) {
return;
}
// Otherwise, carry on.
break;
default:
// For other native event types, do nothing.
return;
}
} else {
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.
fallbackChars = null;
break;
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)) {
fallbackChars = String.fromCharCode(nativeEvent.which);
}
break;
case topLevelTypes.topCompositionEnd:
fallbackChars = nativeEvent.data;
break;
}
// If no changes have occurred to the fallback string, no relevant
// event has fired and we're done.
if (fallbackChars === null) {
return;
}
chars = fallbackChars;
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return;
}
var event = SyntheticInputEvent.getPooled(
eventTypes.beforeInput,
topLevelTargetID,
nativeEvent
);
event.data = chars;
fallbackChars = null;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = BeforeInputEventPlugin;
},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./SyntheticInputEvent":86,"./keyOf":127}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CSSProperty
*/
"use strict";
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
columnCount: true,
fillOpacity: 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
};
/**
* @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;
},{}],4:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CSSPropertyOperations
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var dangerousStyleValue = _dereq_("./dangerousStyleValue");
var hyphenateStyleName = _dereq_("./hyphenateStyleName");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
/**
* 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 (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;
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
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;
},{"./CSSProperty":3,"./dangerousStyleValue":101,"./hyphenateStyleName":118,"./memoizeStringOnly":129}],5:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CallbackQueue
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var invariant = _dereq_("./invariant");
var mixInto = _dereq_("./mixInto");
/**
* 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;
}
mixInto(CallbackQueue, {
/**
* 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;
},{"./PooledClass":26,"./invariant":120,"./mixInto":133}],6:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ChangeEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var isEventSupported = _dereq_("./isEventSupported");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
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;
},{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":76,"./SyntheticEvent":84,"./isEventSupported":121,"./isTextInputElement":123,"./keyOf":127}],7:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ClientReactRootIndex
* @typechecks
*/
"use strict";
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function() {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],8:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CompositionEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var keyOf = _dereq_("./keyOf");
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var useCompositionEvent = (
ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window
);
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. In Korean, for example,
// the compositionend event contains only one character regardless of
// how many characters have been composed since compositionstart.
// We therefore use the fallback data while still using the native
// events as triggers.
var useFallbackData = (
!useCompositionEvent ||
(
'documentMode' in document &&
document.documentMode > 8 &&
document.documentMode <= 11
)
);
var topLevelTypes = EventConstants.topLevelTypes;
var currentComposition = null;
// Events and their corresponding property names.
var eventTypes = {
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
]
}
};
/**
* 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 isFallbackStart(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 isFallbackEnd(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;
}
}
/**
* Helper class stores information about selection and document state
* so we can figure out what changed at a later date.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this.root = root;
this.startSelection = ReactInputSelection.getSelection(root);
this.startValue = this.getText();
}
/**
* Get current text of input.
*
* @return {string}
*/
FallbackCompositionState.prototype.getText = function() {
return this.root.value || this.root[getTextContentAccessor()];
};
/**
* Text that has changed since the start of composition.
*
* @return {string}
*/
FallbackCompositionState.prototype.getData = function() {
var endValue = this.getText();
var prefixLength = this.startSelection.start;
var suffixLength = this.startValue.length - this.startSelection.end;
return endValue.substr(
prefixLength,
endValue.length - suffixLength - prefixLength
);
};
/**
* This plugin creates `onCompositionStart`, `onCompositionUpdate` and
* `onCompositionEnd` events on inputs, textareas and contentEditable
* nodes.
*/
var CompositionEventPlugin = {
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 eventType;
var data;
if (useCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (useFallbackData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = new FallbackCompositionState(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
data = currentComposition.getData();
currentComposition = null;
}
}
}
if (eventType) {
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (data) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = data;
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
};
module.exports = CompositionEventPlugin;
},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":58,"./SyntheticCompositionEvent":82,"./getTextContentAccessor":115,"./keyOf":127}],9:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMChildrenOperations
* @typechecks static-only
*/
"use strict";
var Danger = _dereq_("./Danger");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var invariant = _dereq_("./invariant");
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor();
/**
* 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
);
}
var updateTextContent;
if (textContentAccessor === 'textContent') {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
node.textContent = text;
};
} else {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
// In order to preserve newlines correctly, we can't use .innerText to set
// the contents (see #1080), so we empty the element then append a text node
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (text) {
var doc = node.ownerDocument || document;
node.appendChild(doc.createTextNode(text));
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: updateTextContent,
/**
* 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; update = updates[i]; 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 <p> or <a> tags, 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; update = updates[k]; 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:
updateTextContent(
update.parentNode,
update.textContent
);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"./Danger":12,"./ReactMultiChildUpdateTypes":63,"./getTextContentAccessor":115,"./invariant":120}],10:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
"use strict";
var invariant = _dereq_("./invariant");
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] =
propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE;
DOMProperty.mustUseProperty[propName] =
propConfig & DOMPropertyInjection.MUST_USE_PROPERTY;
DOMProperty.hasSideEffects[propName] =
propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS;
DOMProperty.hasBooleanValue[propName] =
propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE;
DOMProperty.hasNumericValue[propName] =
propConfig & DOMPropertyInjection.HAS_NUMERIC_VALUE;
DOMProperty.hasPositiveNumericValue[propName] =
propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE;
DOMProperty.hasOverloadedBooleanValue[propName] =
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;
},{"./invariant":120}],11:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMPropertyOperations
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var warning = _dereq_("./warning");
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);
}
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
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 ' + name + '. Did you mean ' + 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 processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) +
escapeTextForBrowser(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 escapeTextForBrowser(attributeName);
}
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(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]) {
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
} else {
var propName = DOMProperty.getPropertyName[name];
if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) {
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;
},{"./DOMProperty":10,"./escapeTextForBrowser":104,"./memoizeStringOnly":129,"./warning":143}],12:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createNodesFromMarkup = _dereq_("./createNodesFromMarkup");
var emptyFunction = _dereq_("./emptyFunction");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
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. This is likely a bug in the framework. Please report ' +
'immediately.'
) : 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.
for (var 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 (i = 0; i < renderNodes.length; ++i) {
var renderNode = renderNodes[i];
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. This is likely a bug in the framework. Please report ' +
'immediately.'
) : 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 renderComponentToString().'
) : invariant(oldChild.tagName.toLowerCase() !== 'html'));
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"./ExecutionEnvironment":21,"./createNodesFromMarkup":100,"./emptyFunction":102,"./getMarkupWrap":112,"./invariant":120}],13:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DefaultEventPluginOrder
*/
"use strict";
var keyOf = _dereq_("./keyOf");
/**
* 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({CompositionEventPlugin: null}),
keyOf({BeforeInputEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":127}],14:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EnterLeaveEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var ReactMount = _dereq_("./ReactMount");
var keyOf = _dereq_("./keyOf");
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;
},{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":61,"./SyntheticMouseEvent":88,"./keyOf":127}],15:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventConstants
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
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;
},{"./keyMirror":126}],16:[function(_dereq_,module,exports){
/**
* @providesModule EventListener
* @typechecks
*/
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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;
},{"./emptyFunction":102}],17:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginHub
*/
"use strict";
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
var isEventSupported = _dereq_("./isEventSupported");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* 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 invalid = !InstanceHandle||
!InstanceHandle.traverseTwoPhase ||
!InstanceHandle.traverseEnterLeave;
if (invalid) {
throw new Error('InstanceHandle not injected before use!');
}
}
/**
* 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'));
if ("production" !== "development") {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
if (registrationName === 'onScroll' &&
!isEventSupported('scroll', true)) {
monitorCodeUse('react_no_scroll_event');
console.warn('This browser doesn\'t support the `onScroll` event');
}
}
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 = accumulate(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 = accumulate(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;
},{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./accumulate":94,"./forEachAccumulated":107,"./invariant":120,"./isEventSupported":121,"./monitorCodeUse":134}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginRegistry
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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;
},{"./invariant":120}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var invariant = _dereq_("./invariant");
/**
* 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, executeDispatch) {
forEachEventDispatch(event, executeDispatch);
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;
},{"./EventConstants":15,"./invariant":120}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPropagators
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
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 = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(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 = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(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;
},{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":94,"./forEachAccumulated":107}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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-2014 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 HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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,
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,
// 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,
formNoValidate: HAS_BOOLEAN_VALUE,
frameBorder: MUST_USE_ATTRIBUTE,
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: null,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
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: null,
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,
scrollLeft: MUST_USE_PROPERTY,
scrolling: null,
scrollTop: MUST_USE_PROPERTY,
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: null, // Supported in Mobile Safari for keyboard hints
autoCorrect: null, // Supported in Mobile Safari for keyboard hints
itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
property: null // Supports OG in meta tags
},
DOMAttributeNames: {
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
},{"./DOMProperty":10,"./ExecutionEnvironment":21}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 LinkedValueUtils
* @typechecks static-only
*/
"use strict";
var ReactPropTypes = _dereq_("./ReactPropTypes");
var invariant = _dereq_("./invariant");
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;
}
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;
}
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;
},{"./ReactPropTypes":69,"./invariant":120}],24:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 LocalEventTrapMixin
*/
"use strict";
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
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()));
var listener = ReactBrowserEventEmitter.trapBubbledEvent(
topLevelType,
handlerBaseName,
this.getDOMNode()
);
this._localEventListeners = accumulate(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;
},{"./ReactBrowserEventEmitter":29,"./accumulate":94,"./forEachAccumulated":107,"./invariant":120}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 MobileSafariClickEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var emptyFunction = _dereq_("./emptyFunction");
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;
},{"./EventConstants":15,"./emptyFunction":102}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 PooledClass
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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;
},{"./invariant":120}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 React
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var ReactChildren = _dereq_("./ReactChildren");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var ReactDefaultInjection = _dereq_("./ReactDefaultInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTypes = _dereq_("./ReactPropTypes");
var ReactServerRendering = _dereq_("./ReactServerRendering");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var onlyChild = _dereq_("./onlyChild");
var warning = _dereq_("./warning");
ReactDefaultInjection.inject();
// Specifying arguments isn't necessary since we just use apply anyway, but it
// makes it clear for those actually consuming this API.
function createDescriptor(type, props, children) {
var args = Array.prototype.slice.call(arguments, 1);
return type.apply(null, args);
}
if ("production" !== "development") {
var _warnedForDeprecation = false;
}
var React = {
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
only: onlyChild
},
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
EventPluginUtils.useTouchEvents = shouldUseTouch;
},
createClass: ReactCompositeComponent.createClass,
createDescriptor: function() {
if ("production" !== "development") {
("production" !== "development" ? warning(
_warnedForDeprecation,
'React.createDescriptor is deprecated and will be removed in the ' +
'next version of React. Use React.createElement instead.'
) : null);
_warnedForDeprecation = true;
}
return createDescriptor.apply(this, arguments);
},
createElement: createDescriptor,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
renderComponent: ReactPerf.measure(
'React',
'renderComponent',
ReactMount.renderComponent
),
renderComponentToString: ReactServerRendering.renderComponentToString,
renderComponentToStaticMarkup:
ReactServerRendering.renderComponentToStaticMarkup,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
isValidClass: ReactDescriptor.isValidFactory,
isValidComponent: ReactDescriptor.isValidDescriptor,
withContext: ReactContext.withContext,
__internals: {
Component: ReactComponent,
CurrentOwner: ReactCurrentOwner,
DOMComponent: ReactDOMComponent,
DOMPropertyOperations: DOMPropertyOperations,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
MultiChild: ReactMultiChild,
TextComponent: ReactTextComponent
}
};
if ("production" !== "development") {
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
if (ExecutionEnvironment.canUseDOM &&
window.top === window.self &&
navigator.userAgent.indexOf('Chrome') > -1) {
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 in expectedFeatures) {
if (!expectedFeatures[i]) {
console.error(
'One or more ES5 shim/shams expected by React are not available: ' +
'http://fb.me/react-warning-polyfills'
);
break;
}
}
}
}
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.11.2';
module.exports = React;
},{"./DOMPropertyOperations":11,"./EventPluginUtils":19,"./ExecutionEnvironment":21,"./ReactChildren":30,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactDescriptor":51,"./ReactInstanceHandles":59,"./ReactMount":61,"./ReactMultiChild":62,"./ReactPerf":65,"./ReactPropTypes":69,"./ReactServerRendering":73,"./ReactTextComponent":75,"./onlyChild":135,"./warning":143}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactBrowserComponentMixin
*/
"use strict";
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'getDOMNode(): A component must be mounted to have a DOM node.'
) : invariant(this.isMounted()));
if (ReactEmptyComponent.isNullComponentID(this._rootNodeID)) {
return null;
}
return ReactMount.getNode(this._rootNodeID);
}
};
module.exports = ReactBrowserComponentMixin;
},{"./ReactEmptyComponent":53,"./ReactMount":61,"./invariant":120}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactBrowserEventEmitter
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var isEventSupported = _dereq_("./isEventSupported");
var merge = _dereq_("./merge");
/**
* 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 = merge(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;
},{"./EventConstants":15,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ReactEventEmitterMixin":55,"./ViewportMetrics":93,"./isEventSupported":121,"./merge":130}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactChildren
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
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);
("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 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;
},{"./PooledClass":26,"./traverseAllChildren":142,"./warning":143}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactComponent
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactOwner = _dereq_("./ReactOwner");
var ReactUpdates = _dereq_("./ReactUpdates");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
/**
* Every React component is in one of these life cycles.
*/
var ComponentLifeCycle = keyMirror({
/**
* Mounted components have a DOM node representation and are capable of
* receiving new props.
*/
MOUNTED: null,
/**
* Unmounted components are inactive and cannot receive new props.
*/
UNMOUNTED: null
});
var injected = false;
/**
* 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.
*
* @private
*/
var unmountIDFromEnvironment = null;
/**
* The "image" of a component tree, is the platform specific (typically
* serialized) data that represents a tree of lower level UI building blocks.
* On the web, this "image" is HTML markup which describes a construction of
* low level `div` and `span` nodes. Other platforms may have different
* encoding of this "image". This must be injected.
*
* @private
*/
var mountImageIntoNode = null;
/**
* Components are the basic units of composition in React.
*
* Every component accepts a set of keyed input parameters known as "props" that
* are initialized by the constructor. Once a component is mounted, the props
* can be mutated using `setProps` or `replaceProps`.
*
* Every component is capable of the following operations:
*
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveComponent`
* Updates the rendered DOM nodes to match the given component.
*
* `unmountComponent`
* Releases any resources allocated by this component.
*
* Components can also be "owned" by other components. Being owned by another
* component means being constructed by that component. This is different from
* being the child of a component, which means having a DOM representation that
* is a child of the DOM representation of that component.
*
* @class ReactComponent
*/
var ReactComponent = {
injection: {
injectEnvironment: function(ReactComponentEnvironment) {
("production" !== "development" ? invariant(
!injected,
'ReactComponent: injectEnvironment() can only be called once.'
) : invariant(!injected));
mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode;
unmountIDFromEnvironment =
ReactComponentEnvironment.unmountIDFromEnvironment;
ReactComponent.BackendIDOperations =
ReactComponentEnvironment.BackendIDOperations;
injected = true;
}
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* Injected module that provides ability to mutate individual properties.
* Injected into the base class because many different subclasses need access
* to this.
*
* @internal
*/
BackendIDOperations: null,
/**
* Base functionality for every ReactComponent constructor. Mixed into the
* `ReactComponent` prototype, but exposed statically for easy access.
*
* @lends {ReactComponent.prototype}
*/
Mixin: {
/**
* Checks whether or not this component is mounted.
*
* @return {boolean} True if mounted, false otherwise.
* @final
* @protected
*/
isMounted: function() {
return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
setProps: function(partialProps, callback) {
// Merge with the pending descriptor if it exists, otherwise with existing
// descriptor props.
var descriptor = this._pendingDescriptor || this._descriptor;
this.replaceProps(
merge(descriptor.props, partialProps),
callback
);
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
replaceProps: function(props, callback) {
("production" !== "development" ? invariant(
this.isMounted(),
'replaceProps(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
("production" !== "development" ? invariant(
this._mountDepth === 0,
'replaceProps(...): You called `setProps` or `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(this._mountDepth === 0));
// This is a deoptimized path. We optimize for always having a descriptor.
// This creates an extra internal descriptor.
this._pendingDescriptor = ReactDescriptor.cloneAndReplaceProps(
this._pendingDescriptor || this._descriptor,
props
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* 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 a descriptor.
// This creates an extra internal descriptor.
var descriptor = this._pendingDescriptor || this._descriptor;
this._pendingDescriptor = ReactDescriptor.cloneAndReplaceProps(
descriptor,
merge(descriptor.props, partialProps)
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Base constructor for all React components.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {ReactDescriptor} descriptor
* @internal
*/
construct: function(descriptor) {
// This is the public exposed props object after it has been processed
// with default props. The descriptor's props represents the true internal
// state of the props.
this.props = descriptor.props;
// Record the component responsible for creating this component.
// This is accessible through the descriptor but we maintain an extra
// field for compatibility with devtools and as a way to make an
// incremental update. TODO: Consider deprecating this field.
this._owner = descriptor._owner;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
// See ReactUpdates.
this._pendingCallbacks = null;
// We keep the old descriptor and a reference to the pending descriptor
// to track updates.
this._descriptor = descriptor;
this._pendingDescriptor = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* NOTE: This does not insert any nodes into the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.mountComponent.call(this, ...)`.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy.
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
("production" !== "development" ? invariant(
!this.isMounted(),
'mountComponent(%s, ...): Can only mount an unmounted component. ' +
'Make sure to avoid storing components between renders or reusing a ' +
'single component instance in multiple places.',
rootID
) : invariant(!this.isMounted()));
var props = this._descriptor.props;
if (props.ref != null) {
var owner = this._descriptor._owner;
ReactOwner.addComponentAsRefTo(this, props.ref, owner);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
this._mountDepth = mountDepth;
// Effectively: return '';
},
/**
* Releases any resources allocated by `mountComponent`.
*
* NOTE: This does not remove any nodes from the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.unmountComponent.call(this)`.
*
* @internal
*/
unmountComponent: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'unmountComponent(): Can only unmount a mounted component.'
) : invariant(this.isMounted()));
var props = this.props;
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, this._owner);
}
unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Given a new instance of this component, updates the rendered DOM nodes
* as if that instance was rendered instead.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveComponent.call(this, ...)`.
*
* @param {object} nextComponent Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextDescriptor, transaction) {
("production" !== "development" ? invariant(
this.isMounted(),
'receiveComponent(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
this._pendingDescriptor = nextDescriptor;
this.performUpdateIfNecessary(transaction);
},
/**
* If `_pendingDescriptor` is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
if (this._pendingDescriptor == null) {
return;
}
var prevDescriptor = this._descriptor;
var nextDescriptor = this._pendingDescriptor;
this._descriptor = nextDescriptor;
this.props = nextDescriptor.props;
this._owner = nextDescriptor._owner;
this._pendingDescriptor = null;
this.updateComponent(transaction, prevDescriptor);
},
/**
* Updates the component's currently mounted representation.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevDescriptor
* @internal
*/
updateComponent: function(transaction, prevDescriptor) {
var nextDescriptor = this._descriptor;
// 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 descriptor instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the descriptor.
// 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.
if (nextDescriptor._owner !== prevDescriptor._owner ||
nextDescriptor.props.ref !== prevDescriptor.props.ref) {
if (prevDescriptor.props.ref != null) {
ReactOwner.removeComponentAsRefFrom(
this, prevDescriptor.props.ref, prevDescriptor._owner
);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (nextDescriptor.props.ref != null) {
ReactOwner.addComponentAsRefTo(
this,
nextDescriptor.props.ref,
nextDescriptor._owner
);
}
}
},
/**
* Mounts this component and inserts it into the DOM.
*
* @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
* @final
* @internal
* @see {ReactMount.renderComponent}
*/
mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactUpdates.ReactReconcileTransaction.release(transaction);
},
/**
* @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
* @final
* @private
*/
_mountComponentIntoNode: function(
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = this.mountComponent(rootID, transaction, 0);
mountImageIntoNode(markup, container, shouldReuseMarkup);
},
/**
* Checks if this component is owned by the supplied `owner` component.
*
* @param {ReactComponent} owner Component to check.
* @return {boolean} True if `owners` owns this component.
* @final
* @internal
*/
isOwnedBy: function(owner) {
return this._owner === owner;
},
/**
* Gets another component, that shares the same owner as this one, by ref.
*
* @param {string} ref of a sibling Component.
* @return {?ReactComponent} the actual sibling Component.
* @final
* @internal
*/
getSiblingByRef: function(ref) {
var owner = this._owner;
if (!owner || !owner.refs) {
return null;
}
return owner.refs[ref];
}
}
};
module.exports = ReactComponent;
},{"./ReactDescriptor":51,"./ReactOwner":64,"./ReactUpdates":76,"./invariant":120,"./keyMirror":126,"./merge":130}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
"use strict";
var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/**
* Abstracts away all functionality of `ReactComponent` requires knowledge of
* the browser context.
*/
var ReactComponentBrowserEnvironment = {
ReactReconcileTransaction: ReactReconcileTransaction,
BackendIDOperations: ReactDOMIDOperations,
/**
* 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);
},
/**
* @param {string} markup Markup string to place into the DOM Element.
* @param {DOMElement} container DOM Element to insert markup into.
* @param {boolean} shouldReuseMarkup Should reuse the existing markup in the
* container if possible.
*/
mountImageIntoNode: ReactPerf.measure(
'ReactComponentBrowserEnvironment',
'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) {
if (ReactMarkupChecksum.canReuseMarkup(
markup,
getReactRootElementInContainer(container))) {
return;
} else {
("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.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
if ("production" !== "development") {
console.warn(
'React attempted to use 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.'
);
}
}
}
("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 renderComponentToString() for server rendering.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
setInnerHTML(container, markup);
}
)
};
module.exports = ReactComponentBrowserEnvironment;
},{"./ReactDOMIDOperations":40,"./ReactMarkupChecksum":60,"./ReactMount":61,"./ReactPerf":65,"./ReactReconcileTransaction":71,"./getReactRootElementInContainer":114,"./invariant":120,"./setInnerHTML":138}],33:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactCompositeComponent
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDescriptorValidator = _dereq_("./ReactDescriptorValidator");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactErrorUtils = _dereq_("./ReactErrorUtils");
var ReactOwner = _dereq_("./ReactOwner");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTransferer = _dereq_("./ReactPropTransferer");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var ReactUpdates = _dereq_("./ReactUpdates");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var mapObject = _dereq_("./mapObject");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
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 ReactCompositeComponent 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 `ReactCompositeComponent`, 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 `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* 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) {
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = merge(
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.context
);
Constructor.contextTypes = merge(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) {
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = merge(Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
}
};
function getDeclarationErrorAddendum(component) {
var owner = component._owner || null;
if (owner && owner.constructor && owner.constructor.displayName) {
return ' Check the render method of `' + owner.constructor.displayName +
'`.';
}
return '';
}
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== "development" ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ?
ReactCompositeComponentInterface[name] :
null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: 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,
'ReactCompositeComponentInterface: 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));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== "development" ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). This could potentially cause an infinite ' +
'loop so it is forbidden.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
("production" !== "development" ? invariant(
!ReactDescriptor.isValidFactory(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!ReactDescriptor.isValidFactory(spec)));
("production" !== "development" ? invariant(
!ReactDescriptor.isValidDescriptor(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactDescriptor.isValidDescriptor(spec)));
var proto = Constructor.prototype;
for (var name in spec) {
var property = spec[name];
if (!spec.hasOwnProperty(name)) {
continue;
}
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 ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod =
ReactCompositeComponentInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isAlreadyDefined &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactCompositeComponentInterface[name];
// These cases should already be caught by validateMethodOverride
("production" !== "development" ? invariant(
isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
),
'ReactCompositeComponent: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
) : invariant(isCompositeComponentMethod && (
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 isInherited = name in Constructor;
var result = property;
if (isInherited) {
var existingProperty = Constructor[name];
var existingType = typeof existingProperty;
var propertyType = typeof property;
("production" !== "development" ? invariant(
existingType === 'function' && propertyType === 'function',
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once, but that is only supported ' +
'for functions, which are chained together. This conflict may be ' +
'due to a mixin.',
name
) : invariant(existingType === 'function' && propertyType === 'function'));
result = createChainedFunction(existingProperty, property);
}
Constructor[name] = result;
}
}
/**
* 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 mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== "development" ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
mapObject(two, function(value, key) {
("production" !== "development" ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: %s',
key
) : invariant(one[key] === undefined));
one[key] = value;
});
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;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* 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);
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+------------------------------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+------------------------------------------------------+--------+
* | ^--------+ +------+ +------+ +------+ +--------^ |
* | | | | | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 |
* | | | |PROPS | | PROPS| | STATE| |MOUNTING| |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +--------+ +------+ +------+ +------+ +--------+ |
* | | | |
* +-------+------------------------------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactDescriptor} descriptor
* @final
* @internal
*/
construct: function(descriptor) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
// This is the public post-processed context. The real context and pending
// context lives on the descriptor.
this.context = null;
this._compositeLifeCycleState = null;
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.context = this._processContext(this._descriptor._context);
this.props = this._processProps(this.props);
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== "development" ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent()
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this.componentDidMount, this);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` 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.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== "development" ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== "development"){
("production" !== "development" ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
merge(this._pendingState || this.state, partialState),
callback
);
},
/**
* 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 {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
// 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.
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState.
ReactUpdates.enqueueUpdate(this, callback);
}
},
/**
* 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 = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== "development") {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== "development" ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== "development") {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== "development" ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
return merge(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) {
var defaultProps = this.constructor.defaultProps;
var props;
if (defaultProps) {
props = merge(newProps);
for (var propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
} else {
props = newProps;
}
if ("production" !== "development") {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
}
}
return props;
},
/**
* 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 descriptor
// validation.
var componentName = this.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error =
propTypes[propName](props, propName, componentName, location);
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// renderComponent calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
("production" !== "development" ? warning(false, error.message + addendum) : null);
}
}
}
},
/**
* If any of `_pendingDescriptor`, `_pendingState`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
if (this._pendingDescriptor == null &&
this._pendingState == null &&
!this._pendingForceUpdate) {
return;
}
var nextContext = this.context;
var nextProps = this.props;
var nextDescriptor = this._descriptor;
if (this._pendingDescriptor != null) {
nextDescriptor = this._pendingDescriptor;
nextContext = this._processContext(nextDescriptor._context);
nextProps = this._processProps(nextDescriptor.props);
this._pendingDescriptor = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
var nextState = this._pendingState || this.state;
this._pendingState = null;
try {
var shouldUpdate =
this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("production" !== "development") {
if (typeof shouldUpdate === "undefined") {
console.warn(
(this.constructor.displayName || 'ReactCompositeComponent') +
'.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.'
);
}
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextDescriptor,
nextProps,
nextState,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this._descriptor = nextDescriptor;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextDescriptor._owner;
}
} finally {
this._compositeLifeCycleState = null;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactDescriptor} nextDescriptor Next descriptor
* @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
* @private
*/
_performComponentUpdate: function(
nextDescriptor,
nextProps,
nextState,
nextContext,
transaction
) {
var prevDescriptor = this._descriptor;
var prevProps = this.props;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this._descriptor = nextDescriptor;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextDescriptor._owner;
this.updateComponent(
transaction,
prevDescriptor
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext),
this
);
}
},
receiveComponent: function(nextDescriptor, transaction) {
if (nextDescriptor === this._descriptor &&
nextDescriptor._owner != null) {
// Since descriptors 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 descriptor. We explicitly check for the existence of an owner since
// it's possible for a descriptor created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextDescriptor,
transaction
);
},
/**
* 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
* @param {ReactDescriptor} prevDescriptor
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevParentDescriptor) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevParentDescriptor
);
var prevComponentInstance = this._renderedComponent;
var prevDescriptor = prevComponentInstance._descriptor;
var nextDescriptor = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
prevComponentInstance.receiveComponent(nextDescriptor, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(nextDescriptor);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* 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 {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== "development" ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or during an existing state transition (such as within `render`).'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(
this._descriptor._context
);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
if (renderedComponent === null || renderedComponent === false) {
renderedComponent = ReactEmptyComponent.getEmptyComponent();
ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
} else {
ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
}
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactDescriptor.isValidDescriptor(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = function() {
return method.apply(component, arguments);
};
if ("production" !== "development") {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1);
// 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) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'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 ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* 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, owner) {
this.construct(props, owner);
};
Constructor.prototype = new ReactCompositeComponentBase();
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();
}
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' 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.'
);
}
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
var descriptorFactory = ReactDescriptor.createFactory(Constructor);
if ("production" !== "development") {
return ReactDescriptorValidator.createFactory(
descriptorFactory,
Constructor.propTypes,
Constructor.contextTypes
);
}
return descriptorFactory;
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
},{"./ReactComponent":31,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDescriptor":51,"./ReactDescriptorValidator":52,"./ReactEmptyComponent":53,"./ReactErrorUtils":54,"./ReactOwner":64,"./ReactPerf":65,"./ReactPropTransferer":66,"./ReactPropTypeLocationNames":67,"./ReactPropTypeLocations":68,"./ReactUpdates":76,"./instantiateReactComponent":119,"./invariant":120,"./keyMirror":126,"./mapObject":128,"./merge":130,"./mixInto":133,"./monitorCodeUse":134,"./shouldUpdateReactComponent":140,"./warning":143}],34:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactContext
*/
"use strict";
var merge = _dereq_("./merge");
/**
* 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: {},
/**
* 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) {
var result;
var previousContext = ReactContext.current;
ReactContext.current = merge(previousContext, newContext);
try {
result = scopedCallback();
} finally {
ReactContext.current = previousContext;
}
return result;
}
};
module.exports = ReactContext;
},{"./merge":130}],35:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],36:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOM
* @typechecks static-only
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDescriptorValidator = _dereq_("./ReactDescriptorValidator");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var mergeInto = _dereq_("./mergeInto");
var mapObject = _dereq_("./mapObject");
/**
* 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.
*
* @param {boolean} omitClose True if the close tag should be omitted.
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMComponentClass(omitClose, tag) {
var Constructor = function(descriptor) {
this.construct(descriptor);
};
Constructor.prototype = new ReactDOMComponent(tag, omitClose);
Constructor.prototype.constructor = Constructor;
Constructor.displayName = tag;
var ConvenienceConstructor = ReactDescriptor.createFactory(Constructor);
if ("production" !== "development") {
return ReactDescriptorValidator.createFactory(
ConvenienceConstructor
);
}
return ConvenienceConstructor;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = mapObject({
a: false,
abbr: false,
address: false,
area: true,
article: false,
aside: false,
audio: false,
b: false,
base: true,
bdi: false,
bdo: false,
big: false,
blockquote: false,
body: false,
br: true,
button: false,
canvas: false,
caption: false,
cite: false,
code: false,
col: true,
colgroup: false,
data: false,
datalist: false,
dd: false,
del: false,
details: false,
dfn: false,
dialog: false,
div: false,
dl: false,
dt: false,
em: false,
embed: true,
fieldset: false,
figcaption: false,
figure: false,
footer: false,
form: false, // NOTE: Injected, see `ReactDOMForm`.
h1: false,
h2: false,
h3: false,
h4: false,
h5: false,
h6: false,
head: false,
header: false,
hr: true,
html: false,
i: false,
iframe: false,
img: true,
input: true,
ins: false,
kbd: false,
keygen: true,
label: false,
legend: false,
li: false,
link: true,
main: false,
map: false,
mark: false,
menu: false,
menuitem: false, // NOTE: Close tag should be omitted, but causes problems.
meta: true,
meter: false,
nav: false,
noscript: false,
object: false,
ol: false,
optgroup: false,
option: false,
output: false,
p: false,
param: true,
picture: false,
pre: false,
progress: false,
q: false,
rp: false,
rt: false,
ruby: false,
s: false,
samp: false,
script: false,
section: false,
select: false,
small: false,
source: true,
span: false,
strong: false,
style: false,
sub: false,
summary: false,
sup: false,
table: false,
tbody: false,
td: false,
textarea: false, // NOTE: Injected, see `ReactDOMTextarea`.
tfoot: false,
th: false,
thead: false,
time: false,
title: false,
tr: false,
track: true,
u: false,
ul: false,
'var': false,
video: false,
wbr: true,
// SVG
circle: false,
defs: false,
ellipse: false,
g: false,
line: false,
linearGradient: false,
mask: false,
path: false,
pattern: false,
polygon: false,
polyline: false,
radialGradient: false,
rect: false,
stop: false,
svg: false,
text: false,
tspan: false
}, createDOMComponentClass);
var injection = {
injectComponentClasses: function(componentClasses) {
mergeInto(ReactDOM, componentClasses);
}
};
ReactDOM.injection = injection;
module.exports = ReactDOM;
},{"./ReactDOMComponent":38,"./ReactDescriptor":51,"./ReactDescriptorValidator":52,"./mapObject":128,"./mergeInto":132}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMButton
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var keyMirror = _dereq_("./keyMirror");
// Store a reference to the <button> `ReactDOMComponent`.
var button = ReactDOM.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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMButton',
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;
},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":126}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMComponent
* @typechecks static-only
*/
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMProperty = _dereq_("./DOMProperty");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
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;
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
("production" !== "development" ? invariant(
props.children == null || props.dangerouslySetInnerHTML == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
) : invariant(props.children == null || props.dangerouslySetInnerHTML == 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.'
) : invariant(props.style == null || typeof props.style === 'object'));
}
function putListener(id, registrationName, listener, transaction) {
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
);
}
/**
* @constructor ReactDOMComponent
* @extends ReactComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag, omitClose) {
this._tagOpen = '<' + tag;
this._tagClose = omitClose ? '' : '</' + tag + '>';
this.tagName = tag.toUpperCase();
}
ReactDOMComponent.Mixin = {
/**
* 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
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} The computed markup.
*/
mountComponent: ReactPerf.measure(
'ReactDOMComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
assertValidProps(this.props);
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction) +
this._tagClose
);
}
),
/**
* 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.props;
var ret = this._tagOpen;
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 = props.style = merge(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
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var contentToUse =
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
}
}
return '';
},
receiveComponent: function(nextDescriptor, transaction) {
if (nextDescriptor === this._descriptor &&
nextDescriptor._owner != null) {
// Since descriptors 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 descriptor. We explicitly check for the existence of an owner since
// it's possible for a descriptor created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextDescriptor,
transaction
);
},
/**
* 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 {ReactDescriptor} prevDescriptor
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactDOMComponent',
'updateComponent',
function(transaction, prevDescriptor) {
assertValidProps(this._descriptor.props);
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevDescriptor
);
this._updateDOMProperties(prevDescriptor.props, transaction);
this._updateDOMChildren(prevDescriptor.props, transaction);
}
),
/**
* 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.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = nextProps.style = merge(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)) {
ReactComponent.BackendIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
ReactComponent.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) {
var nextProps = this.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);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
ReactComponent.BackendIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction);
}
},
/**
* 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);
ReactComponent.Mixin.unmountComponent.call(this);
}
};
mixInto(ReactDOMComponent, ReactComponent.Mixin);
mixInto(ReactDOMComponent, ReactDOMComponent.Mixin);
mixInto(ReactDOMComponent, ReactMultiChild.Mixin);
mixInto(ReactDOMComponent, ReactBrowserComponentMixin);
module.exports = ReactDOMComponent;
},{"./CSSPropertyOperations":4,"./DOMProperty":10,"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactMount":61,"./ReactMultiChild":62,"./ReactPerf":65,"./escapeTextForBrowser":104,"./invariant":120,"./keyOf":127,"./merge":130,"./mixInto":133}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMForm
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <form> `ReactDOMComponent`.
var form = ReactDOM.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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMForm',
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 this.transferPropsTo(form(null, this.props.children));
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset');
this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit');
}
});
module.exports = ReactDOMForm;
},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],40:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMChildrenOperations = _dereq_("./DOMChildrenOperations");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
/**
* 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
* `ReactComponent.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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyProcessChildrenUpdates',
function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
)
};
module.exports = ReactDOMIDOperations;
},{"./CSSPropertyOperations":4,"./DOMChildrenOperations":9,"./DOMPropertyOperations":11,"./ReactMount":61,"./ReactPerf":65,"./invariant":120,"./setInnerHTML":138}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMImg
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <img> `ReactDOMComponent`.
var img = ReactDOM.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 = ReactCompositeComponent.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;
},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],42:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMInput
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
// Store a reference to the <input> `ReactDOMComponent`.
var input = ReactDOM.input;
var instancesByReactID = {};
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMInput',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
checked: this.props.defaultChecked || false,
value: defaultValue != null ? defaultValue : null
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.defaultChecked = null;
props.defaultValue = null;
var value = LinkedValueUtils.getValue(this);
props.value = value != null ? value : this.state.value;
var checked = LinkedValueUtils.getChecked(this);
props.checked = checked != null ? checked : this.state.checked;
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) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({
checked: event.target.checked,
value: event.target.value
});
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));
// In some cases, this will actually change the `checked` state value.
// In other cases, there's no change but this forces a reconcile upon
// which componentDidUpdate will reset the DOM property to whatever it
// should be.
otherInstance.setState({
checked: false
});
}
}
return returnValue;
}
});
module.exports = ReactDOMInput;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":61,"./invariant":120,"./merge":130}],43:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMOption
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var warning = _dereq_("./warning");
// Store a reference to the <option> `ReactDOMComponent`.
var option = ReactDOM.option;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactCompositeComponent.createClass({
displayName: 'ReactDOMOption',
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;
},{"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./warning":143}],44:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMSelect
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var merge = _dereq_("./merge");
// Store a reference to the <select> `ReactDOMComponent`.
var select = ReactDOM.select;
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return;
}
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.")
);
}
}
}
/**
* If `value` is supplied, updates <option> elements on mount and update.
* @param {ReactComponent} component Instance of ReactDOMSelect
* @param {?*} propValue For uncontrolled components, null/undefined. For
* controlled components, a string (or with `multiple`, a list of strings).
* @private
*/
function updateOptions(component, propValue) {
var multiple = component.props.multiple;
var value = propValue != null ? propValue : component.state.value;
var options = component.getDOMNode().options;
var selectedValue, i, l;
if (multiple) {
selectedValue = {};
for (i = 0, l = value.length; i < l; ++i) {
selectedValue['' + value[i]] = true;
}
} else {
selectedValue = '' + value;
}
for (i = 0, l = options.length; i < l; i++) {
var selected = multiple ?
selectedValue.hasOwnProperty(options[i].value) :
options[i].value === selectedValue;
if (selected !== options[i].selected) {
options[i].selected = selected;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* string. If `multiple` is true, the prop must be an array of strings.
*
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMSelect',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
getInitialState: function() {
return {value: this.props.defaultValue || (this.props.multiple ? [] : '')};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.multiple && nextProps.multiple) {
this.setState({value: [this.state.value]});
} else if (this.props.multiple && !nextProps.multiple) {
this.setState({value: this.state.value[0]});
}
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentDidMount: function() {
updateOptions(this, LinkedValueUtils.getValue(this));
},
componentDidUpdate: function(prevProps) {
var value = LinkedValueUtils.getValue(this);
var prevMultiple = !!prevProps.multiple;
var multiple = !!this.props.multiple;
if (value != null || prevMultiple !== multiple) {
updateOptions(this, value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
var selectedValue;
if (this.props.multiple) {
selectedValue = [];
var options = event.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = event.target.value;
}
this.setState({value: selectedValue});
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./merge":130}],45:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMSelection
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
/**
* 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();
if (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;
detectionRange.detach();
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) {
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);
}
range.detach();
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && document.selection;
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"./ExecutionEnvironment":21,"./getNodeForCharacterOffset":113,"./getTextContentAccessor":115}],46:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMTextarea
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
var warning = _dereq_("./warning");
// Store a reference to the <textarea> `ReactDOMComponent`.
var textarea = ReactDOM.textarea;
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMTextarea',
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)
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(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) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({value: event.target.value});
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":120,"./merge":130,"./warning":143}],47:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultBatchingStrategy
*/
"use strict";
var ReactUpdates = _dereq_("./ReactUpdates");
var Transaction = _dereq_("./Transaction");
var emptyFunction = _dereq_("./emptyFunction");
var mixInto = _dereq_("./mixInto");
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();
}
mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin);
mixInto(ReactDefaultBatchingStrategyTransaction, {
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) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b);
} else {
transaction.perform(callback, null, a, b);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./ReactUpdates":76,"./Transaction":92,"./emptyFunction":102,"./mixInto":133}],48:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultInjection
*/
"use strict";
var BeforeInputEventPlugin = _dereq_("./BeforeInputEventPlugin");
var ChangeEventPlugin = _dereq_("./ChangeEventPlugin");
var ClientReactRootIndex = _dereq_("./ClientReactRootIndex");
var CompositionEventPlugin = _dereq_("./CompositionEventPlugin");
var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var HTMLDOMPropertyConfig = _dereq_("./HTMLDOMPropertyConfig");
var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponentBrowserEnvironment =
_dereq_("./ReactComponentBrowserEnvironment");
var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMButton = _dereq_("./ReactDOMButton");
var ReactDOMForm = _dereq_("./ReactDOMForm");
var ReactDOMImg = _dereq_("./ReactDOMImg");
var ReactDOMInput = _dereq_("./ReactDOMInput");
var ReactDOMOption = _dereq_("./ReactDOMOption");
var ReactDOMSelect = _dereq_("./ReactDOMSelect");
var ReactDOMTextarea = _dereq_("./ReactDOMTextarea");
var ReactEventListener = _dereq_("./ReactEventListener");
var ReactInjection = _dereq_("./ReactInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var SelectEventPlugin = _dereq_("./SelectEventPlugin");
var ServerReactRootIndex = _dereq_("./ServerReactRootIndex");
var SimpleEventPlugin = _dereq_("./SimpleEventPlugin");
var SVGDOMPropertyConfig = _dereq_("./SVGDOMPropertyConfig");
var createFullPageComponent = _dereq_("./createFullPageComponent");
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,
CompositionEventPlugin: CompositionEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.DOM.injectComponentClasses({
button: ReactDOMButton,
form: ReactDOMForm,
img: ReactDOMImg,
input: ReactDOMInput,
option: ReactDOMOption,
select: ReactDOMSelect,
textarea: ReactDOMTextarea,
html: createFullPageComponent(ReactDOM.html),
head: createFullPageComponent(ReactDOM.head),
body: createFullPageComponent(ReactDOM.body)
});
// This needs to happen after createFullPageComponent() otherwise the mixin
// gets double injected.
ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent(ReactDOM.noscript);
ReactInjection.Updates.injectReconcileTransaction(
ReactComponentBrowserEnvironment.ReactReconcileTransaction
);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("production" !== "development") {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = _dereq_("./ReactDefaultPerf");
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"./BeforeInputEventPlugin":2,"./ChangeEventPlugin":6,"./ClientReactRootIndex":7,"./CompositionEventPlugin":8,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./HTMLDOMPropertyConfig":22,"./MobileSafariClickEventPlugin":25,"./ReactBrowserComponentMixin":28,"./ReactComponentBrowserEnvironment":32,"./ReactDOM":36,"./ReactDOMButton":37,"./ReactDOMForm":39,"./ReactDOMImg":41,"./ReactDOMInput":42,"./ReactDOMOption":43,"./ReactDOMSelect":44,"./ReactDOMTextarea":46,"./ReactDefaultBatchingStrategy":47,"./ReactDefaultPerf":49,"./ReactEventListener":56,"./ReactInjection":57,"./ReactInstanceHandles":59,"./ReactMount":61,"./SVGDOMPropertyConfig":77,"./SelectEventPlugin":78,"./ServerReactRootIndex":79,"./SimpleEventPlugin":80,"./createFullPageComponent":99}],49:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultPerf
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var performanceNow = _dereq_("./performanceNow");
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'
);
},
printWasted: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(
measurements,
true
);
console.table(summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
}));
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() {var args=Array.prototype.slice.call(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 (moduleName === 'ReactDOMIDOperations' ||
moduleName === 'ReactComponentBrowserEnvironment') {
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' && (
fnName === 'mountComponent' ||
fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
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.constructor.displayName,
owner: this._owner ? this._owner.constructor.displayName : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"./DOMProperty":10,"./ReactDefaultPerfAnalysis":50,"./ReactMount":61,"./ReactPerf":65,"./performanceNow":137}],50:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultPerfAnalysis
*/
var merge = _dereq_("./merge");
// 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 = merge(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 = merge(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 = merge(measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggerd
// 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;
},{"./merge":130}],51:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 ReactDescriptor
*/
"use strict";
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var merge = _dereq_("./merge");
var warning = _dereq_("./warning");
/**
* 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 ' + key + ' property of the component. ' +
'Mutate the existing props object instead.'
) : 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} descriptor
*/
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
}
}
/**
* Transfer static properties from the source to the target. Functions are
* rebound to have this reflect the original source.
*/
function proxyStaticMethods(target, source) {
if (typeof source !== 'function') {
return;
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
var value = source[key];
if (typeof value === 'function') {
var bound = value.bind(source);
// Copy any properties defined on the function, such as `isRequired` on
// a PropTypes validator. (mergeInto refuses to work on functions.)
for (var k in value) {
if (value.hasOwnProperty(k)) {
bound[k] = value[k];
}
}
target[key] = bound;
} else {
target[key] = value;
}
}
}
}
/**
* Base constructor for all React descriptors. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @param {*} type
* @internal
*/
var ReactDescriptor = function() {};
if ("production" !== "development") {
defineMutationMembrane(ReactDescriptor.prototype);
}
ReactDescriptor.createFactory = function(type) {
var descriptorPrototype = Object.create(ReactDescriptor.prototype);
var factory = function(props, children) {
// For consistency we currently allocate a new object for every descriptor.
// This protects the descriptor from being mutated by the original props
// object being mutated. It also protects the original props object from
// being mutated by children arguments and default props. This behavior
// comes with a performance cost and could be deprecated in the future.
// It could also be optimized with a smarter JSX transform.
if (props == null) {
props = {};
} else if (typeof props === 'object') {
props = merge(props);
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 1;
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 + 1];
}
props.children = childArray;
}
// Initialize the descriptor object
var descriptor = Object.create(descriptorPrototype);
// Record the component responsible for creating this descriptor.
descriptor._owner = ReactCurrentOwner.current;
// TODO: Deprecate withContext, and then the context becomes accessible
// through the owner.
descriptor._context = ReactContext.current;
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.
descriptor._store = { validated: false, props: props };
// 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(descriptor);
return descriptor;
}
}
descriptor.props = props;
return descriptor;
};
// Currently we expose the prototype of the descriptor so that
// <Foo /> instanceof Foo works. This is controversial pattern.
factory.prototype = descriptorPrototype;
// Expose the type on the factory and the prototype so that it can be
// easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for
// static methods like <Foo />.type.staticMethod();
// This should not be named constructor since this may not be the function
// that created the descriptor, and it may not even be a constructor.
factory.type = type;
descriptorPrototype.type = type;
proxyStaticMethods(factory, type);
// Expose a unique constructor on the prototype is that this works with type
// systems that compare constructor properties: <Foo />.constructor === Foo
// This may be controversial since it requires a known factory function.
descriptorPrototype.constructor = factory;
return factory;
};
ReactDescriptor.cloneAndReplaceProps = function(oldDescriptor, newProps) {
var newDescriptor = Object.create(oldDescriptor.constructor.prototype);
// It's important that this property order matches the hidden class of the
// original descriptor to maintain perf.
newDescriptor._owner = oldDescriptor._owner;
newDescriptor._context = oldDescriptor._context;
if ("production" !== "development") {
newDescriptor._store = {
validated: oldDescriptor._store.validated,
props: newProps
};
if (useMutationMembrane) {
Object.freeze(newDescriptor);
return newDescriptor;
}
}
newDescriptor.props = newProps;
return newDescriptor;
};
/**
* Checks if a value is a valid descriptor constructor.
*
* @param {*}
* @return {boolean}
* @public
*/
ReactDescriptor.isValidFactory = function(factory) {
return typeof factory === 'function' &&
factory.prototype instanceof ReactDescriptor;
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactDescriptor.isValidDescriptor = function(object) {
return object instanceof ReactDescriptor;
};
module.exports = ReactDescriptor;
},{"./ReactContext":34,"./ReactCurrentOwner":35,"./merge":130,"./warning":143}],52:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 ReactDescriptorValidator
*/
/**
* ReactDescriptorValidator provides a wrapper around a descriptor factory
* which validates the props passed to the descriptor. 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 ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* 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 = {
'react_key_warning': {},
'react_numeric_key_warning': {}
};
var ownerHasMonitoredObjectMap = {};
var loggedTypeFailures = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
/**
* 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 && current.constructor.displayName || undefined;
}
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component 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 {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validateExplicitKey(component, parentType) {
if (component._store.validated || component.props.key != null) {
return;
}
component._store.validated = true;
warnAndMonitorForKeyUse(
'react_key_warning',
'Each child in an array should have a unique "key" prop.',
component,
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 {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validatePropertyKey(name, component, parentType) {
if (!NUMERIC_PROPERTY_REGEX.test(name)) {
return;
}
warnAndMonitorForKeyUse(
'react_numeric_key_warning',
'Child objects should have non-numeric keys so ordering is preserved.',
component,
parentType
);
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} warningID The id used when logging.
* @param {string} message The base warning that gets output.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function warnAndMonitorForKeyUse(warningID, message, component, parentType) {
var ownerName = getCurrentOwnerDisplayName();
var parentName = parentType.displayName;
var useName = ownerName || parentName;
var memoizer = ownerHasKeyUseWarning[warningID];
if (memoizer.hasOwnProperty(useName)) {
return;
}
memoizer[useName] = true;
message += ownerName ?
(" Check the render method of " + ownerName + ".") :
(" Check the renderComponent 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 childOwnerName = null;
if (component._owner && component._owner !== ReactCurrentOwner.current) {
// Name of the component that originally created this child.
childOwnerName = component._owner.constructor.displayName;
message += (" It was passed a child from " + childOwnerName + ".");
}
message += ' See http://fb.me/react-warning-keys for more information.';
monitorCodeUse(warningID, {
component: useName,
componentOwner: childOwnerName
});
console.warn(message);
}
/**
* Log that we're using an object map. We're considering deprecating this
* feature and replace it with proper Map and ImmutableMap data structures.
*
* @internal
*/
function monitorUseOfObjectMap() {
var currentName = getCurrentOwnerDisplayName() || '';
if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
return;
}
ownerHasMonitoredObjectMap[currentName] = true;
monitorCodeUse('react_object_map_children');
}
/**
* Ensure that every component 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 {*} component Statically passed child of any type.
* @param {*} parentType component's parent's type.
* @return {boolean}
*/
function validateChildKeys(component, parentType) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactDescriptor.isValidDescriptor(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactDescriptor.isValidDescriptor(component)) {
// This component was passed in a valid location.
component._store.validated = true;
} else if (component && typeof component === 'object') {
monitorUseOfObjectMap();
for (var name in component) {
validatePropertyKey(name, component[name], 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 {
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;
// This will soon use the warning module
monitorCodeUse(
'react_failed_descriptor_type_check',
{ message: error.message }
);
}
}
}
}
var ReactDescriptorValidator = {
/**
* Wraps a descriptor factory function in another function which validates
* the props and context of the descriptor and warns about any failed type
* checks.
*
* @param {function} factory The original descriptor factory
* @param {object?} propTypes A prop type definition set
* @param {object?} contextTypes A context type definition set
* @return {object} The component descriptor, which may be invalid.
* @private
*/
createFactory: function(factory, propTypes, contextTypes) {
var validatedFactory = function(props, children) {
var descriptor = factory.apply(this, arguments);
for (var i = 1; i < arguments.length; i++) {
validateChildKeys(arguments[i], descriptor.type);
}
var name = descriptor.type.displayName;
if (propTypes) {
checkPropTypes(
name,
propTypes,
descriptor.props,
ReactPropTypeLocations.prop
);
}
if (contextTypes) {
checkPropTypes(
name,
contextTypes,
descriptor._context,
ReactPropTypeLocations.context
);
}
return descriptor;
};
validatedFactory.prototype = factory.prototype;
validatedFactory.type = factory.type;
// Copy static properties
for (var key in factory) {
if (factory.hasOwnProperty(key)) {
validatedFactory[key] = factory[key];
}
}
return validatedFactory;
}
};
module.exports = ReactDescriptorValidator;
},{"./ReactCurrentOwner":35,"./ReactDescriptor":51,"./ReactPropTypeLocations":68,"./monitorCodeUse":134}],53:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 ReactEmptyComponent
*/
"use strict";
var invariant = _dereq_("./invariant");
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 = emptyComponent;
}
};
/**
* @return {ReactComponent} component The injected empty component.
*/
function getEmptyComponent() {
("production" !== "development" ? invariant(
component,
'Trying to return null from a render, but no null placeholder component ' +
'was injected.'
) : invariant(component));
return component();
}
/**
* 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 = {
deregisterNullComponentID: deregisterNullComponentID,
getEmptyComponent: getEmptyComponent,
injection: ReactEmptyComponentInjection,
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID
};
module.exports = ReactEmptyComponent;
},{"./invariant":120}],54:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],55:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactEventEmitterMixin
*/
"use strict";
var EventPluginHub = _dereq_("./EventPluginHub");
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;
},{"./EventPluginHub":17}],56:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactEventListener
* @typechecks static-only
*/
"use strict";
var EventListener = _dereq_("./EventListener");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var PooledClass = _dereq_("./PooledClass");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactUpdates = _dereq_("./ReactUpdates");
var getEventTarget = _dereq_("./getEventTarget");
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
var mixInto = _dereq_("./mixInto");
/**
* 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 = [];
}
mixInto(TopLevelCallbackBookKeeping, {
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;
}
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;
}
return EventListener.capture(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
monitorScrollValue: function(refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
EventListener.listen(window, 'resize', 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;
},{"./EventListener":16,"./ExecutionEnvironment":21,"./PooledClass":26,"./ReactInstanceHandles":59,"./ReactMount":61,"./ReactUpdates":76,"./getEventTarget":111,"./getUnboundedScrollPosition":116,"./mixInto":133}],57:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInjection
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var EventPluginHub = _dereq_("./EventPluginHub");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactPerf = _dereq_("./ReactPerf");
var ReactRootIndex = _dereq_("./ReactRootIndex");
var ReactUpdates = _dereq_("./ReactUpdates");
var ReactInjection = {
Component: ReactComponent.injection,
CompositeComponent: ReactCompositeComponent.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
DOM: ReactDOM.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"./DOMProperty":10,"./EventPluginHub":17,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEmptyComponent":53,"./ReactPerf":65,"./ReactRootIndex":72,"./ReactUpdates":76}],58:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInputSelection
*/
"use strict";
var ReactDOMSelection = _dereq_("./ReactDOMSelection");
var containsNode = _dereq_("./containsNode");
var focusNode = _dereq_("./focusNode");
var getActiveElement = _dereq_("./getActiveElement");
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;
},{"./ReactDOMSelection":45,"./containsNode":96,"./focusNode":106,"./getActiveElement":108}],59:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInstanceHandles
* @typechecks static-only
*/
"use strict";
var ReactRootIndex = _dereq_("./ReactRootIndex");
var invariant = _dereq_("./invariant");
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;
for (var 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;
},{"./ReactRootIndex":72,"./invariant":120}],60:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMarkupChecksum
*/
"use strict";
var adler32 = _dereq_("./adler32");
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;
},{"./adler32":95}],61:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMount
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactPerf = _dereq_("./ReactPerf");
var containsNode = _dereq_("./containsNode");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
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 = [];
/**
* @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];
}
/**
* 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;
}
/**
* Mounting is the process of initializing a React component by creatings its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.renderComponent(
* 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 {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextComponent,
container,
callback) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps, 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 {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: ReactPerf.measure(
'ReactMount',
'_renderNewRootComponent',
function(
nextComponent,
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(nextComponent);
var reactRootID = ReactMount._registerComponent(
componentInstance,
container
);
componentInstance.mountComponentIntoNode(
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 {ReactDescriptor} nextDescriptor Component descriptor to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderComponent: function(nextDescriptor, container, callback) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(nextDescriptor),
'renderComponent(): Invalid component descriptor.%s',
(
ReactDescriptor.isValidFactory(nextDescriptor) ?
' Instead of passing a component class, make sure to instantiate ' +
'it first by calling it with props.' :
// Check if it quacks like a descriptor
typeof nextDescriptor.props !== "undefined" ?
' This may be caused by unintentionally loading two independent ' +
'copies of React.' :
''
)
) : invariant(ReactDescriptor.isValidDescriptor(nextDescriptor)));
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevDescriptor = prevComponent._descriptor;
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
return ReactMount._updateRootComponent(
prevComponent,
nextDescriptor,
container,
callback
);
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;
var component = ReactMount._renderNewRootComponent(
nextDescriptor,
container,
shouldReuseMarkup
);
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) {
return ReactMount.renderComponent(constructor(props), 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);
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) {
instance.unmountComponent();
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 {
console.warn(
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
);
}
}
}
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 <p> ' +
'or <a> tags, 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));
},
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
purgeID: purgeID
};
module.exports = ReactMount;
},{"./DOMProperty":10,"./ReactBrowserEventEmitter":29,"./ReactCurrentOwner":35,"./ReactDescriptor":51,"./ReactInstanceHandles":59,"./ReactPerf":65,"./containsNode":96,"./getReactRootElementInContainer":114,"./instantiateReactComponent":119,"./invariant":120,"./shouldUpdateReactComponent":140,"./warning":143}],62:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMultiChild
* @typechecks static-only
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var flattenChildren = _dereq_("./flattenChildren");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
/**
* 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) {
ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates(
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) {
var children = flattenChildren(nestedChildren);
var mountImages = [];
var index = 0;
this._renderedChildren = children;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name)) {
// The rendered children must be turned into instances as they're
// mounted.
var childInstance = instantiateReactComponent(child);
children[name] = childInstance;
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = childInstance.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
childInstance._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.
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) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : 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) {
var nextChildren = flattenChildren(nextNestedChildren);
var prevChildren = this._renderedChildren;
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 prevDescriptor = prevChild && prevChild._descriptor;
var nextDescriptor = nextChildren[name];
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild.receiveComponent(nextDescriptor, transaction);
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.
var nextChildInstance = instantiateReactComponent(nextDescriptor);
this._mountChildByNameAtIndex(
nextChildInstance, name, nextIndex, transaction
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren[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;
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
// TODO: When is this not true?
if (renderedChild.unmountComponent) {
renderedChild.unmountComponent();
}
}
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) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountIndex = index;
this.createChild(child, mountImage);
this._renderedChildren = this._renderedChildren || {};
this._renderedChildren[name] = child;
},
/**
* 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;
child.unmountComponent();
delete this._renderedChildren[name];
}
}
};
module.exports = ReactMultiChild;
},{"./ReactComponent":31,"./ReactMultiChildUpdateTypes":63,"./flattenChildren":105,"./instantiateReactComponent":119,"./shouldUpdateReactComponent":140}],63:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMultiChildUpdateTypes
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
/**
* 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;
},{"./keyMirror":126}],64:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactOwner
*/
"use strict";
var emptyObject = _dereq_("./emptyObject");
var invariant = _dereq_("./invariant");
/**
* 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.refs[ref] === component) {
owner.detachRef(ref);
}
},
/**
* A ReactComponent must mix this in to have refs.
*
* @lends {ReactOwner.prototype}
*/
Mixin: {
construct: function() {
this.refs = emptyObject;
},
/**
* 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) {
("production" !== "development" ? invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
) : invariant(component.isOwnedBy(this)));
var refs = this.refs === emptyObject ? (this.refs = {}) : this.refs;
refs[ref] = component;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
delete this.refs[ref];
}
}
};
module.exports = ReactOwner;
},{"./emptyObject":103,"./invariant":120}],65:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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,
/**
* 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;
return function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
}
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;
},{}],66:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTransferer
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
var invariant = _dereq_("./invariant");
var joinClasses = _dereq_("./joinClasses");
var merge = _dereq_("./merge");
/**
* Creates a transfer strategy that will merge prop values using the supplied
* `mergeStrategy`. If a prop was previously unset, this just sets it.
*
* @param {function} mergeStrategy
* @return {function}
*/
function createTransferStrategy(mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
var transferStrategyMerge = createTransferStrategy(function(a, b) {
// `merge` overrides the first object's (`props[key]` above) keys using the
// second object's (`value`) keys. An object's style's existing `propA` would
// get overridden. Flip the order here.
return merge(b, a);
});
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
* NOTE: if you add any more exceptions to this list you should be sure to
* update `cloneWithProps()` accordingly.
*/
var TransferStrategies = {
/**
* Never transfer `children`.
*/
children: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Never transfer the `key` prop.
*/
key: emptyFunction,
/**
* Never transfer the `ref` prop.
*/
ref: emptyFunction,
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: transferStrategyMerge
};
/**
* Mutates the first argument by transferring the properties from the second
* argument.
*
* @param {object} props
* @param {object} newProps
* @return {object}
*/
function transferInto(props, newProps) {
for (var thisKey in newProps) {
if (!newProps.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) {
transferStrategy(props, thisKey, newProps[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = newProps[thisKey];
}
}
return props;
}
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* Merge two props objects using TransferStrategies.
*
* @param {object} oldProps original props (they take precedence)
* @param {object} newProps new props to merge in
* @return {object} a new object containing both sets of props merged.
*/
mergeProps: function(oldProps, newProps) {
return transferInto(merge(oldProps), newProps);
},
/**
* @lends {ReactPropTransferer.prototype}
*/
Mixin: {
/**
* Transfer props from this component to a target component.
*
* Props that do not have an explicit transfer strategy will be transferred
* only if the target component does not already have the prop set.
*
* This is usually used to pass down props to a returned root component.
*
* @param {ReactDescriptor} descriptor Component receiving the properties.
* @return {ReactDescriptor} The supplied `component`.
* @final
* @protected
*/
transferPropsTo: function(descriptor) {
("production" !== "development" ? invariant(
descriptor._owner === this,
'%s: You can\'t call transferPropsTo() on a component that you ' +
'don\'t own, %s. This usually means you are calling ' +
'transferPropsTo() on a component passed in as props or children.',
this.constructor.displayName,
descriptor.type.displayName
) : invariant(descriptor._owner === this));
// Because descriptors are immutable we have to merge into the existing
// props object rather than clone it.
transferInto(descriptor.props, this.props);
return descriptor;
}
}
};
module.exports = ReactPropTransferer;
},{"./emptyFunction":102,"./invariant":120,"./joinClasses":125,"./merge":130}],67:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypeLocationNames
*/
"use strict";
var ReactPropTypeLocationNames = {};
if ("production" !== "development") {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],68:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypeLocations
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"./keyMirror":126}],69:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypes
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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 ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
component: createComponentTypeChecker(),
instanceOf: createInstanceTypeChecker,
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
renderable: createRenderableTypeChecker(),
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 + "`.")
);
}
} 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 createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns());
}
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 createChainableTypeChecker(validate);
}
function createComponentTypeChecker() {
function validate(props, propName, componentName, location) {
if (!ReactDescriptor.isValidDescriptor(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a React component.")
);
}
}
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 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;
}
}
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 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;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`.")
);
}
return createChainableTypeChecker(validate);
}
function createRenderableTypeChecker() {
function validate(props, propName, componentName, location) {
if (!isRenderable(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a renderable prop.")
);
}
}
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 createChainableTypeChecker(validate, 'expected `object`');
}
function isRenderable(propValue) {
switch(typeof propValue) {
// TODO: this was probably written with the assumption that we're not
// returning `this.props.component` directly from `render`. This is
// currently not supported but we should, to make it consistent.
case 'number':
case 'string':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isRenderable);
}
if (ReactDescriptor.isValidDescriptor(propValue)) {
return true;
}
for (var k in propValue) {
if (!isRenderable(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;
},{"./ReactDescriptor":51,"./ReactPropTypeLocationNames":67,"./emptyFunction":102}],70:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPutListenerQueue
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var mixInto = _dereq_("./mixInto");
function ReactPutListenerQueue() {
this.listenersToPut = [];
}
mixInto(ReactPutListenerQueue, {
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;
},{"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./mixInto":133}],71:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactReconcileTransaction
* @typechecks static-only
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var mixInto = _dereq_("./mixInto");
/**
* 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;
}
};
mixInto(ReactReconcileTransaction, Transaction.Mixin);
mixInto(ReactReconcileTransaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./CallbackQueue":5,"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./ReactInputSelection":58,"./ReactPutListenerQueue":70,"./Transaction":92,"./mixInto":133}],72:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactRootIndex
* @typechecks
*/
"use strict";
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function(_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],73:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactServerRenderingTransaction =
_dereq_("./ReactServerRenderingTransaction");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
/**
* @param {ReactComponent} component
* @return {string} the HTML markup
*/
function renderComponentToString(component) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(component),
'renderComponentToString(): You must pass a valid ReactComponent.'
) : invariant(ReactDescriptor.isValidDescriptor(component)));
("production" !== "development" ? invariant(
!(arguments.length === 2 && typeof arguments[1] === 'function'),
'renderComponentToString(): This function became synchronous and now ' +
'returns the generated markup. Please remove the second parameter.'
) : invariant(!(arguments.length === 2 && typeof arguments[1] === 'function')));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
var markup = componentInstance.mountComponent(id, transaction, 0);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
/**
* @param {ReactComponent} component
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderComponentToStaticMarkup(component) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(component),
'renderComponentToStaticMarkup(): You must pass a valid ReactComponent.'
) : invariant(ReactDescriptor.isValidDescriptor(component)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
return componentInstance.mountComponent(id, transaction, 0);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
module.exports = {
renderComponentToString: renderComponentToString,
renderComponentToStaticMarkup: renderComponentToStaticMarkup
};
},{"./ReactDescriptor":51,"./ReactInstanceHandles":59,"./ReactMarkupChecksum":60,"./ReactServerRenderingTransaction":74,"./instantiateReactComponent":119,"./invariant":120}],74:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 ReactServerRenderingTransaction
* @typechecks
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var CallbackQueue = _dereq_("./CallbackQueue");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var emptyFunction = _dereq_("./emptyFunction");
var mixInto = _dereq_("./mixInto");
/**
* 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;
}
};
mixInto(ReactServerRenderingTransaction, Transaction.Mixin);
mixInto(ReactServerRenderingTransaction, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"./CallbackQueue":5,"./PooledClass":26,"./ReactPutListenerQueue":70,"./Transaction":92,"./emptyFunction":102,"./mixInto":133}],75:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactTextComponent
* @typechecks static-only
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var mixInto = _dereq_("./mixInto");
/**
* 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 ReactTextComponent
* @extends ReactComponent
* @internal
*/
var ReactTextComponent = function(descriptor) {
this.construct(descriptor);
};
mixInto(ReactTextComponent, ReactComponent.Mixin);
mixInto(ReactTextComponent, ReactBrowserComponentMixin);
mixInto(ReactTextComponent, {
/**
* 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
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
var escapedText = escapeTextForBrowser(this.props);
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 {object} nextComponent Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextComponent, transaction) {
var nextProps = nextComponent.props;
if (nextProps !== this.props) {
this.props = nextProps;
ReactComponent.BackendIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps
);
}
}
});
module.exports = ReactDescriptor.createFactory(ReactTextComponent);
},{"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactComponent":31,"./ReactDescriptor":51,"./escapeTextForBrowser":104,"./mixInto":133}],76:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactUpdates
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactPerf = _dereq_("./ReactPerf");
var Transaction = _dereq_("./Transaction");
var invariant = _dereq_("./invariant");
var mixInto = _dereq_("./mixInto");
var warning = _dereq_("./warning");
var dirtyComponents = [];
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(null);
this.reconcileTransaction =
ReactUpdates.ReactReconcileTransaction.getPooled();
}
mixInto(ReactUpdatesFlushTransaction, Transaction.Mixin);
mixInto(ReactUpdatesFlushTransaction, {
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) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b);
}
/**
* Array comparator for ReactComponents by owner depth
*
* @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 mountDepthComparator(c1, c2) {
return c1._mountDepth - c2._mountDepth;
}
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(mountDepthComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, ignore them
// TODO: Queue unmounts in the same list to avoid this happening at all
var component = dirtyComponents[i];
if (component.isMounted()) {
// 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;
component.performUpdateIfNecessary(transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(
callbacks[j],
component
);
}
}
}
}
}
var flushBatchedUpdates = ReactPerf.measure(
'ReactUpdates',
'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.
while (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
}
);
/**
* 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, callback) {
("production" !== "development" ? invariant(
!callback || typeof callback === "function",
'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(!callback || typeof callback === "function"));
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, callback);
return;
}
dirtyComponents.push(component);
if (callback) {
if (component._pendingCallbacks) {
component._pendingCallbacks.push(callback);
} else {
component._pendingCallbacks = [callback];
}
}
}
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
};
module.exports = ReactUpdates;
},{"./CallbackQueue":5,"./PooledClass":26,"./ReactCurrentOwner":35,"./ReactPerf":65,"./Transaction":92,"./invariant":120,"./mixInto":133,"./warning":143}],77:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SVGDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
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;
},{"./DOMProperty":10}],78:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SelectEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getActiveElement = _dereq_("./getActiveElement");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
var shallowEqual = _dereq_("./shallowEqual");
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 (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
} else {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
/**
* 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;
}
// 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;
},{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":58,"./SyntheticEvent":84,"./getActiveElement":108,"./isTextInputElement":123,"./keyOf":127,"./shallowEqual":139}],79:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],80:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SimpleEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent");
var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var SyntheticDragEvent = _dereq_("./SyntheticDragEvent");
var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent");
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
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 topLevelType in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType];
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false.
*
* @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);
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.
if (nativeEvent.charCode === 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;
},{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":81,"./SyntheticDragEvent":83,"./SyntheticEvent":84,"./SyntheticFocusEvent":85,"./SyntheticKeyboardEvent":87,"./SyntheticMouseEvent":88,"./SyntheticTouchEvent":89,"./SyntheticUIEvent":90,"./SyntheticWheelEvent":91,"./invariant":120,"./keyOf":127}],81:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticClipboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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;
},{"./SyntheticEvent":84}],82:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticCompositionEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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;
},{"./SyntheticEvent":84}],83:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticDragEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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;
},{"./SyntheticMouseEvent":88}],84:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticEvent
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var emptyFunction = _dereq_("./emptyFunction");
var getEventTarget = _dereq_("./getEventTarget");
var merge = _dereq_("./merge");
var mergeInto = _dereq_("./mergeInto");
/**
* @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;
}
mergeInto(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
event.stopPropagation ? event.stopPropagation() : 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);
mergeInto(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = merge(Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"./PooledClass":26,"./emptyFunction":102,"./getEventTarget":111,"./merge":130,"./mergeInto":132}],85:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticFocusEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
/**
* @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;
},{"./SyntheticUIEvent":90}],86:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 SyntheticInputEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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;
},{"./SyntheticEvent":84}],87:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticKeyboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventKey = _dereq_("./getEventKey");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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.
if (event.type === 'keypress') {
// IE8 does not implement "charCode", but "keyCode" has the correct value.
return 'charCode' in event ? event.charCode : event.keyCode;
}
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. There is no need to determine the type of the event
// as `keyCode` and `charCode` are either aliased or default to zero.
return event.keyCode || event.charCode;
}
};
/**
* @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;
},{"./SyntheticUIEvent":90,"./getEventKey":109,"./getEventModifierState":110}],88:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticMouseEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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;
},{"./SyntheticUIEvent":90,"./ViewportMetrics":93,"./getEventModifierState":110}],89:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticTouchEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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;
},{"./SyntheticUIEvent":90,"./getEventModifierState":110}],90:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticUIEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getEventTarget = _dereq_("./getEventTarget");
/**
* @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;
},{"./SyntheticEvent":84,"./getEventTarget":111}],91:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticWheelEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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;
},{"./SyntheticMouseEvent":88}],92:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 Transaction
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* `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 upates.
*
* 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;
},{"./invariant":120}],93:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ViewportMetrics
*/
"use strict";
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function() {
var scrollPosition = getUnboundedScrollPosition(window);
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{"./getUnboundedScrollPosition":116}],94:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 accumulate
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Accumulates items that must not be null or undefined.
*
* This is used to conserve memory by avoiding array allocations.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulate(current, next) {
("production" !== "development" ? invariant(
next != null,
'accumulate(...): Accumulated items must be not be null or undefined.'
) : invariant(next != null));
if (current == null) {
return next;
} else {
// 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) {
return current.concat(next);
} else {
if (nextIsArray) {
return [current].concat(next);
} else {
return [current, next];
}
}
}
}
module.exports = accumulate;
},{"./invariant":120}],95:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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 reasonable 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;
},{}],96:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 containsNode
* @typechecks
*/
var isTextNode = _dereq_("./isTextNode");
/*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;
},{"./isTextNode":124}],97:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 copyProperties
*/
/**
* Copy properties from one or more objects (up to 5) into the first object.
* This is a shallow copy. It mutates the first object and also returns it.
*
* NOTE: `arguments` has a very significant performance penalty, which is why
* we don't support unlimited arguments.
*/
function copyProperties(obj, a, b, c, d, e, f) {
obj = obj || {};
if ("production" !== "development") {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString != 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
},{}],98:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createArrayFrom
* @typechecks
*/
var toArray = _dereq_("./toArray");
/**
* 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 createArrayFrom = require('createArrayFrom');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFrom(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 createArrayFrom(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFrom;
},{"./toArray":141}],99:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createFullPageComponent
* @typechecks
*/
"use strict";
// Defeat circular references by requiring this directly.
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var invariant = _dereq_("./invariant");
/**
* 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 {function} componentClass convenience constructor to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(componentClass) {
var FullPageComponent = ReactCompositeComponent.createClass({
displayName: 'ReactFullPageComponent' + (
componentClass.type.displayName || ''
),
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 this.transferPropsTo(componentClass(null, this.props.children));
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
},{"./ReactCompositeComponent":33,"./invariant":120}],100:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createArrayFrom = _dereq_("./createArrayFrom");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
/**
* 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));
createArrayFrom(scripts).forEach(handleScript);
}
var nodes = createArrayFrom(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"./ExecutionEnvironment":21,"./createArrayFrom":98,"./getMarkupWrap":112,"./invariant":120}],101:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 dangerousStyleValue
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
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;
},{"./CSSProperty":3}],102:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 emptyFunction
*/
var copyProperties = _dereq_("./copyProperties");
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() {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
module.exports = emptyFunction;
},{"./copyProperties":97}],103:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== "development") {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],104:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 escapeTextForBrowser
* @typechecks static-only
*/
"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 escapeTextForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextForBrowser;
},{}],105:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 flattenChildren
*/
"use strict";
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
/**
* @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);
("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;
},{"./traverseAllChildren":142,"./warning":143}],106:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 focusNode
*/
"use strict";
/**
* IE8 throws if an input/textarea is disabled and we try to focus it.
* Focus only when necessary.
*
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
if (!node.disabled) {
node.focus();
}
}
module.exports = focusNode;
},{}],107:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],108:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],109:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getEventKey
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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 `which`/`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') {
// Create the character from the `charCode` ourselves and use as an almost
// perfect replacement.
var charCode = 'charCode' in nativeEvent ?
nativeEvent.charCode :
nativeEvent.keyCode;
// 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';
}
("production" !== "development" ? invariant(false, "Unexpected keyboard event type: %s", nativeEvent.type) : invariant(false));
}
module.exports = getEventKey;
},{"./invariant":120}],110:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 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;
},{}],111:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],112:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getMarkupWrap
*/
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var invariant = _dereq_("./invariant");
/**
* 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;
},{"./ExecutionEnvironment":21,"./invariant":120}],113:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],114:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],115:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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;
},{"./ExecutionEnvironment":21}],116:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],117:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],118:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 hyphenateStyleName
* @typechecks
*/
"use strict";
var hyphenate = _dereq_("./hyphenate");
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
* > hyphenate('MozTransition')
* < "-moz-transition"
* > hyphenate('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;
},{"./hyphenate":117}],119:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 instantiateReactComponent
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Validate a `componentDescriptor`. This should be exposed publicly in a follow
* up diff.
*
* @param {object} descriptor
* @return {boolean} Returns true if this is a valid descriptor of a Component.
*/
function isValidComponentDescriptor(descriptor) {
return (
descriptor &&
typeof descriptor.type === 'function' &&
typeof descriptor.type.prototype.mountComponent === 'function' &&
typeof descriptor.type.prototype.receiveComponent === 'function'
);
}
/**
* Given a `componentDescriptor` create an instance that will actually be
* mounted. Currently it just extracts an existing clone from composite
* components but this is an implementation detail which will change.
*
* @param {object} descriptor
* @return {object} A new instance of componentDescriptor's constructor.
* @protected
*/
function instantiateReactComponent(descriptor) {
// TODO: Make warning
// if (__DEV__) {
("production" !== "development" ? invariant(
isValidComponentDescriptor(descriptor),
'Only React Components are valid for mounting.'
) : invariant(isValidComponentDescriptor(descriptor)));
// }
return new descriptor.type(descriptor);
}
module.exports = instantiateReactComponent;
},{"./invariant":120}],120:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],121:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 isEventSupported
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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;
},{"./ExecutionEnvironment":21}],122:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],123:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],124:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 isTextNode
* @typechecks
*/
var isNode = _dereq_("./isNode");
/**
* @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;
},{"./isNode":122}],125:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 joinClasses
* @typechecks static-only
*/
"use strict";
/**
* Combines multiple className strings into one.
* http://jsperf.com/joinclasses-args-vs-array
*
* @param {...?string} classes
* @return {string}
*/
function joinClasses(className/*, ... */) {
if (!className) {
className = '';
}
var nextClass;
var argLength = arguments.length;
if (argLength > 1) {
for (var ii = 1; ii < argLength; ii++) {
nextClass = arguments[ii];
nextClass && (className += ' ' + nextClass);
}
}
return className;
}
module.exports = joinClasses;
},{}],126:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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;
},{"./invariant":120}],127:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],128:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mapObject
*/
"use strict";
/**
* For each key/value pair, invokes callback func and constructs a resulting
* object which contains, for every key in obj, values that are the result of
* of invoking the function:
*
* func(value, key, iteration)
*
* Grepable names:
*
* function objectMap()
* function objMap()
*
* @param {?object} obj Object to map keys over
* @param {function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function mapObject(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, obj[key], key, i++);
}
}
return ret;
}
module.exports = mapObject;
},{}],129:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],130:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 merge
*/
"use strict";
var mergeInto = _dereq_("./mergeInto");
/**
* Shallow merges two structures into a return value, without mutating either.
*
* @param {?object} one Optional object with properties to merge from.
* @param {?object} two Optional object with properties to merge from.
* @return {object} The shallow extension of one by two.
*/
var merge = function(one, two) {
var result = {};
mergeInto(result, one);
mergeInto(result, two);
return result;
};
module.exports = merge;
},{"./mergeInto":132}],131:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mergeHelpers
*
* requiresPolyfills: Array.isArray
*/
"use strict";
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
/**
* Maximum number of levels to traverse. Will catch circular structures.
* @const
*/
var MAX_MERGE_DEPTH = 36;
/**
* We won't worry about edge cases like new String('x') or new Boolean(true).
* Functions are considered terminals, and arrays are not.
* @param {*} o The item/object/value to test.
* @return {boolean} true iff the argument is a terminal.
*/
var isTerminal = function(o) {
return typeof o !== 'object' || o === null;
};
var mergeHelpers = {
MAX_MERGE_DEPTH: MAX_MERGE_DEPTH,
isTerminal: isTerminal,
/**
* Converts null/undefined values into empty object.
*
* @param {?Object=} arg Argument to be normalized (nullable optional)
* @return {!Object}
*/
normalizeMergeArg: function(arg) {
return arg === undefined || arg === null ? {} : arg;
},
/**
* If merging Arrays, a merge strategy *must* be supplied. If not, it is
* likely the caller's fault. If this function is ever called with anything
* but `one` and `two` being `Array`s, it is the fault of the merge utilities.
*
* @param {*} one Array to merge into.
* @param {*} two Array to merge from.
*/
checkMergeArrayArgs: function(one, two) {
("production" !== "development" ? invariant(
Array.isArray(one) && Array.isArray(two),
'Tried to merge arrays, instead got %s and %s.',
one,
two
) : invariant(Array.isArray(one) && Array.isArray(two)));
},
/**
* @param {*} one Object to merge into.
* @param {*} two Object to merge from.
*/
checkMergeObjectArgs: function(one, two) {
mergeHelpers.checkMergeObjectArg(one);
mergeHelpers.checkMergeObjectArg(two);
},
/**
* @param {*} arg
*/
checkMergeObjectArg: function(arg) {
("production" !== "development" ? invariant(
!isTerminal(arg) && !Array.isArray(arg),
'Tried to merge an object, instead got %s.',
arg
) : invariant(!isTerminal(arg) && !Array.isArray(arg)));
},
/**
* @param {*} arg
*/
checkMergeIntoObjectArg: function(arg) {
("production" !== "development" ? invariant(
(!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg),
'Tried to merge into an object, instead got %s.',
arg
) : invariant((!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg)));
},
/**
* Checks that a merge was not given a circular object or an object that had
* too great of depth.
*
* @param {number} Level of recursion to validate against maximum.
*/
checkMergeLevel: function(level) {
("production" !== "development" ? invariant(
level < MAX_MERGE_DEPTH,
'Maximum deep merge depth exceeded. You may be attempting to merge ' +
'circular structures in an unsupported way.'
) : invariant(level < MAX_MERGE_DEPTH));
},
/**
* Checks that the supplied merge strategy is valid.
*
* @param {string} Array merge strategy.
*/
checkArrayStrategy: function(strategy) {
("production" !== "development" ? invariant(
strategy === undefined || strategy in mergeHelpers.ArrayStrategies,
'You must provide an array strategy to deep merge functions to ' +
'instruct the deep merge how to resolve merging two arrays.'
) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies));
},
/**
* Set of possible behaviors of merge algorithms when encountering two Arrays
* that must be merged together.
* - `clobber`: The left `Array` is ignored.
* - `indexByIndex`: The result is achieved by recursively deep merging at
* each index. (not yet supported.)
*/
ArrayStrategies: keyMirror({
Clobber: true,
IndexByIndex: true
})
};
module.exports = mergeHelpers;
},{"./invariant":120,"./keyMirror":126}],132:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mergeInto
* @typechecks static-only
*/
"use strict";
var mergeHelpers = _dereq_("./mergeHelpers");
var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
var checkMergeIntoObjectArg = mergeHelpers.checkMergeIntoObjectArg;
/**
* Shallow merges two structures by mutating the first parameter.
*
* @param {object|function} one Object to be merged into.
* @param {?object} two Optional object with properties to merge from.
*/
function mergeInto(one, two) {
checkMergeIntoObjectArg(one);
if (two != null) {
checkMergeObjectArg(two);
for (var key in two) {
if (!two.hasOwnProperty(key)) {
continue;
}
one[key] = two[key];
}
}
}
module.exports = mergeInto;
},{"./mergeHelpers":131}],133:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mixInto
*/
"use strict";
/**
* Simply copies properties to the prototype.
*/
var mixInto = function(constructor, methodBag) {
var methodName;
for (methodName in methodBag) {
if (!methodBag.hasOwnProperty(methodName)) {
continue;
}
constructor.prototype[methodName] = methodBag[methodName];
}
};
module.exports = mixInto;
},{}],134:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 monitorCodeUse
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue a warning or refactor. It accepts an event
* name which may only contain the characters [a-z0-9_] and an optional data
* object with further information.
*/
function monitorCodeUse(eventName, data) {
("production" !== "development" ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
},{"./invariant":120}],135:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 onlyChild
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var invariant = _dereq_("./invariant");
/**
* 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(
ReactDescriptor.isValidDescriptor(children),
'onlyChild must be passed a children with exactly one child.'
) : invariant(ReactDescriptor.isValidDescriptor(children)));
return children;
}
module.exports = onlyChild;
},{"./ReactDescriptor":51,"./invariant":120}],136:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 performance
* @typechecks
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance =
window.performance ||
window.msPerformance ||
window.webkitPerformance;
}
module.exports = performance || {};
},{"./ExecutionEnvironment":21}],137:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 performanceNow
* @typechecks
*/
var performance = _dereq_("./performance");
/**
* 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;
},{"./performance":136}],138:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 setInnerHTML
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
/**
* 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;
};
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 (html.match(/^[ \r\n\t\f]/) ||
html[0] === '<' && (
html.indexOf('<noscript') !== -1 ||
html.indexOf('<script') !== -1 ||
html.indexOf('<style') !== -1 ||
html.indexOf('<meta') !== -1 ||
html.indexOf('<link') !== -1)) {
// 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;
},{"./ExecutionEnvironment":21}],139:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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'a keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],140:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 shouldUpdateReactComponent
* @typechecks static-only
*/
"use strict";
/**
* Given a `prevDescriptor` and `nextDescriptor`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are descriptors. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevDescriptor
* @param {?object} nextDescriptor
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevDescriptor, nextDescriptor) {
if (prevDescriptor && nextDescriptor &&
prevDescriptor.type === nextDescriptor.type && (
(prevDescriptor.props && prevDescriptor.props.key) ===
(nextDescriptor.props && nextDescriptor.props.key)
) && prevDescriptor._owner === nextDescriptor._owner) {
return true;
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{}],141:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 toArray
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFrom.
*
* @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;
},{"./invariant":120}],142:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 traverseAllChildren
*/
"use strict";
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var invariant = _dereq_("./invariant");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that:
* 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`.
* 2. it('should fail when supplied duplicate key', function() {
* 3. That a single child and an array with one item have the same key pattern.
* });
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
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.props && component.props.key != null) {
// Explicit key
return wrapUserProvidedKey(component.props.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.
*/
var traverseAllChildrenImpl =
function(children, nameSoFar, indexSoFar, callback, traverseContext) {
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var nextName = (
nameSoFar +
(nameSoFar ? SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, i)
);
var nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
// 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
var storageName =
isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar;
if (children == null || type === 'boolean') {
// All of the above are perceived as null.
callback(traverseContext, null, storageName, indexSoFar);
subtreeCount = 1;
} else if (children.type && children.type.prototype &&
children.type.prototype.mountComponentIntoNode) {
callback(traverseContext, children, storageName, indexSoFar);
subtreeCount = 1;
} else {
if (type === 'object') {
("production" !== "development" ? invariant(
!children || children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
) : invariant(!children || children.nodeType !== 1));
for (var key in children) {
if (children.hasOwnProperty(key)) {
subtreeCount += traverseAllChildrenImpl(
children[key],
(
nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(key) + SUBSEPARATOR +
getComponentKey(children[key], 0)
),
indexSoFar + subtreeCount,
callback,
traverseContext
);
}
}
} else if (type === 'string') {
var normalizedText = ReactTextComponent(children);
callback(traverseContext, normalizedText, storageName, indexSoFar);
subtreeCount += 1;
} else if (type === 'number') {
var normalizedNumber = ReactTextComponent('' + children);
callback(traverseContext, normalizedNumber, storageName, indexSoFar);
subtreeCount += 1;
}
}
}
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;
},{"./ReactInstanceHandles":59,"./ReactTextComponent":75,"./invariant":120}],143:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 warning
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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 ) {var args=Array.prototype.slice.call(arguments,2);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
var argIndex = 0;
console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}));
}
};
}
module.exports = warning;
},{"./emptyFunction":102}]},{},[27])
(27)
}); |
src/app.js | fjoder/indecision-app | import React from 'react';
import ReactDOM from 'react-dom';
import IndecisionApp from './components/IndecisionApp';
import 'normalize.css/normalize.css';
import './styles/styles.scss';
ReactDOM.render(<IndecisionApp />, document.getElementById('app'));
|
src/parser/demonhunter/havoc/modules/talents/MasterOfTheGlaives.js | sMteX/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import Events from 'parser/core/Events';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
/**
* Example Report: https://www.warcraftlogs.com/reports/QDMVJtvnBz43NZLk/#fight=2&source=1
*/
class MasterOfTheGlaives extends Analyzer{
slows = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.MASTER_OF_THE_GLAIVE_TALENT.id);
if (!this.active) {
return;
}
this.addEventListener(Events.applydebuff.by(SELECTED_PLAYER).spell(SPELLS.MASTER_OF_THE_GLAIVE_DEBUFF), this.countingSlows);
}
countingSlows(event) {
this.slows += 1;
}
statistic(){
return (
<TalentStatisticBox
talent={SPELLS.MASTER_OF_THE_GLAIVE_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(6)}
value={<>{this.slows} <small>slows provided</small></>}
/>
);
}
}
export default MasterOfTheGlaives;
|
packages/mineral-ui-icons/src/IconLeakRemove.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLeakRemove(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97A8.99 8.99 0 0 1 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5A11.044 11.044 0 0 0 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43A6.922 6.922 0 0 0 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46A8.98 8.98 0 0 1 21 12v-2c-2.06 0-3.98.58-5.62 1.56z"/>
</g>
</Icon>
);
}
IconLeakRemove.displayName = 'IconLeakRemove';
IconLeakRemove.category = 'image';
|
javascript/AddOn/Waiting.js | AppStateESS/stories | import React from 'react'
import PropTypes from 'prop-types'
const Waiting = (props) => {
let message
if (props.message.length === 0) {
message = <span>Loading {props.label}...</span>
} else {
message = props.message
}
return (
<div className="lead text-center">
<i className="fa fa-cog fa-spin fa-lg"></i> {message}
</div>
)
}
Waiting.propTypes = {
label: PropTypes.string,
message: PropTypes.string,
}
Waiting.defaultProps = {
message: '',
label: '',
}
export default Waiting
|
examples/todomvc/test/components/Footer.spec.js | camsong/redux | import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Footer from '../../components/Footer'
import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters'
function setup(propOverrides) {
const props = Object.assign({
completedCount: 0,
activeCount: 0,
filter: SHOW_ALL,
onClearCompleted: expect.createSpy(),
onShow: expect.createSpy()
}, propOverrides)
const renderer = TestUtils.createRenderer()
renderer.render(<Footer {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output
}
}
function getTextContent(elem) {
const children = Array.isArray(elem.props.children) ?
elem.props.children : [ elem.props.children ]
return children.reduce(function concatText(out, child) {
// Children are either elements or text strings
return out + (child.props ? getTextContent(child) : child)
}, '')
}
describe('components', () => {
describe('Footer', () => {
it('should render container', () => {
const { output } = setup()
expect(output.type).toBe('footer')
expect(output.props.className).toBe('footer')
})
it('should display active count when 0', () => {
const { output } = setup({ activeCount: 0 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('No items left')
})
it('should display active count when above 0', () => {
const { output } = setup({ activeCount: 1 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('1 item left')
})
it('should render filters', () => {
const { output } = setup()
const [ , filters ] = output.props.children
expect(filters.type).toBe('ul')
expect(filters.props.className).toBe('filters')
expect(filters.props.children.length).toBe(3)
filters.props.children.forEach(function checkFilter(filter, i) {
expect(filter.type).toBe('li')
const a = filter.props.children
expect(a.props.className).toBe(i === 0 ? 'selected' : '')
expect(a.props.children).toBe({
0: 'All',
1: 'Active',
2: 'Completed'
}[i])
})
})
it('should call onShow when a filter is clicked', () => {
const { output, props } = setup()
const [ , filters ] = output.props.children
const filterLink = filters.props.children[1].props.children
filterLink.props.onClick({})
expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE)
})
it('shouldnt show clear button when no completed todos', () => {
const { output } = setup({ completedCount: 0 })
const [ , , clear ] = output.props.children
expect(clear).toBe(undefined)
})
it('should render clear button when completed todos', () => {
const { output } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
expect(clear.type).toBe('button')
expect(clear.props.children).toBe('Clear completed')
})
it('should call onClearCompleted on clear button click', () => {
const { output, props } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
clear.props.onClick({})
expect(props.onClearCompleted).toHaveBeenCalled()
})
})
})
|
src/containers/DevTools/DevTools.js | ptim/react-redux-universal-hot-example | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="Q">
<LogMonitor />
</DockMonitor>
);
|
app/containers/AdminFournisseur/components/ProduitForm.js | Proxiweb/react-boilerplate | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { reduxForm, Field } from 'redux-form';
import MenuItem from 'material-ui/MenuItem';
import CustomSelectField from 'components/CustomSelectField';
import { TextField } from 'redux-form-material-ui';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import { convertFromHTML, ContentState, convertToRaw } from 'draft-js';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styles from './styles.css';
import RaisedButton from 'material-ui/RaisedButton';
const options = {
options: ['inline', 'list', 'textAlign', 'link', 'remove', 'history'],
inline: {
inDropdown: false,
className: undefined,
options: ['bold', 'italic', 'underline', 'strikethrough'],
},
list: {
inDropdown: false,
className: undefined,
options: ['unordered', 'ordered'],
},
};
const renderSelectField = datas => (
{ input, label, meta: { touched, error }, ...custom } // eslint-disable-line
) =>
<CustomSelectField
floatingLabelText={label}
errorText={touched && error}
{...input}
onChange={(event, index, value) => input.onChange(value)}
{...custom}
>
{datas.map(data => <MenuItem key={data.value} value={data.value} primaryText={data.label} />)}
</CustomSelectField>;
const renderUnitesConservation = renderSelectField([
{
value: 'jours',
label: 'jours',
},
{
value: 'semaines',
label: 'semaines',
},
{
value: 'mois',
label: 'mois',
},
]);
const renderTva = renderSelectField([
{
value: 5.5,
label: '5.5',
},
{
value: 10,
label: '10',
},
{
value: 20,
label: '20',
},
]);
const renderTypesProduits = typesProduits =>
renderSelectField(
Object.keys(typesProduits).map(value => ({
value: typesProduits[value].id,
label: typesProduits[value].nom,
}))
);
const renderClassementComplementaire = categoriesSecondaires =>
renderSelectField(
categoriesSecondaires.map(value => ({
value,
label: value,
}))
);
class ProduitForm extends Component {
// eslint-disable-line react/prefer-stateless-function
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
changeDescription: PropTypes.func.isRequired,
typesProduits: PropTypes.object.isRequired,
valeurs: PropTypes.object.isRequired,
pending: PropTypes.bool.isRequired,
pristine: PropTypes.bool.isRequired,
};
constructor(props) {
super(props);
const { description } = this.props.initialValues; // eslint-disable-line
this.state = {
rawHtml: this.getInitialHTML(description),
};
}
state = {
rawHtml: null,
};
onEditorChange = editorContent => {
const html = draftToHtml(editorContent);
this.props.changeDescription(html);
this.setState({ ...this.state, html });
};
getInitialHTML(html) {
const contentBlocks = convertFromHTML(html);
const contentState = ContentState.createFromBlockArray(contentBlocks);
return convertToRaw(contentState);
}
// handleTypeProduitChange = (event, index, value) => {
// this.setState({ ...this.state, typeProduitSelected: value });
// }
render() {
const { handleSubmit, pending, pristine, typesProduits, valeurs } = this.props;
const categoriesSecondaires = valeurs.produit && valeurs.produit.values.typeProduitId
? typesProduits[valeurs.produit.values.typeProduitId].categoriesSecondaires
: [];
return (
<form onSubmit={handleSubmit}>
<div className="row" style={{ minHeight: '400px' }}>
<div className="col-md-12">
<Field floatingLabelText="Nom" name="nom" component={TextField} fullWidth />
</div>
<div className="col-md-12">
<Field
style={{ display: 'none' }}
floatingLabelText="Description"
name="description"
component={TextField}
fullWidth
/>
<p className={styles.label}>Description</p>
<Editor
editorClassName={styles.editorClass}
toolbar={options}
onChange={this.onEditorChange}
initialContentState={this.state.rawHtml}
/>
</div>
<div className="col-md-3">
<Field floatingLabelText="Tva" name="tva" component={renderTva} fullWidth />
</div>
<div className="col-md-3">
<Field floatingLabelText="Stock" name="stock" component={TextField} fullWidth />
</div>
<div className="col-md-3">
<Field
floatingLabelText="Conservation garantie"
name="garantieConservation.nombre"
component={TextField}
fullWidth
/>
</div>
<div className="col-md-3">
<Field
floatingLabelText="Unité"
name="garantieConservation.type"
component={renderUnitesConservation}
fullWidth
/>
</div>
<div className="col-md-6">
<Field
floatingLabelText="Type de produits"
name="typeProduitId"
component={renderTypesProduits(typesProduits)}
fullWidth
/>
</div>
{categoriesSecondaires.length > 0 &&
<div className="col-md-6">
<Field
floatingLabelText="Classement complémentaire"
name="typeProduitSecondaire"
component={renderClassementComplementaire(categoriesSecondaires)}
fullWidth
/>
</div>}
{categoriesSecondaires.length > 0 &&
<div className="col-md-6">
<Field
floatingLabelText="Classement complémentaire bis"
name="typeProduitTernaire"
component={TextField}
fullWidth
/>
</div>}
<div className="col-md-6">
<Field floatingLabelText="Référence" name="ref" component={TextField} fullWidth />
</div>
</div>
{!pristine &&
<div className="row center-md">
<div className={`col-md-8 ${styles.formFooter}`} style={{ minHeight: 52 }}>
<RaisedButton type="submit" label="Valider" primary fullWidth disabled={pending} />
</div>
</div>}
</form>
);
}
}
const produitForm = reduxForm({
form: 'produit',
})(ProduitForm);
export default produitForm;
|
client/components/Landing.js | MusicConnectionMachine/VisualizationG6 | import React from 'react'
import Searchbar from './Searchbar'
import LandingWidgets from './static/LandingWidgets'
import CheckOurStats from './static/CheckOurStats'
import headerImage from '../../style/img/logo/logo-landing.svg'
import '../../style/landing.scss'
const Landing = React.createClass({
render () {
return (
<div className='landing'>
<div className='container-fluid'>
<div className='center-block text-center text-white margin-top-10-p animated fadeIn'>
<img src={headerImage} alt='Music Connection Machine Logo' style={{maxWidth: '600px', width: '100%', paddingTop: '30px'}} />
<h3 className='margin-top-5-p' style={{color: 'rgb(51, 51, 51)'}}>Discover connections between composers, musicians and music works.</h3>
</div>
<div className='row margin-top-10-p searchfield center-block'>
<Searchbar displayHelpText />
</div>
</div>
<LandingWidgets />
<CheckOurStats />
</div>
)
}
})
export default Landing
|
src/modules/modals/APIRespondModal/APIRespondModal.js | hellofresh/janus-dashboard | import React from 'react'
import PropTypes from 'prop-types'
import Modal from '../../../components/Modal/Modal'
import Button from '../../../components/Button/Button'
const propTypes = {
closeModal: PropTypes.func.isRequired,
isOpen: PropTypes.bool.isRequired,
message: PropTypes.string.isRequired,
redirectOnClose: PropTypes.func
}
const defaultProps = {
message: '',
statusText: ''
}
const APIRespondModal = ({
closeModal,
isOpen,
message,
redirectOnClose
}) => {
const handleClose = () => {
closeModal()
if (redirectOnClose) {
redirectOnClose()
}
}
if (!message) return null
return (
<Modal
closeModal={handleClose}
message={message}
show={isOpen}
title='Ooops!'
buttons={[
<Button key='ok' mod='primary' onClick={handleClose}>OK</Button>
]}
/>
)
}
APIRespondModal.propTypes = propTypes
APIRespondModal.defaultProps = defaultProps
export default APIRespondModal
|
[5]. Utils/ViewUtils.js | knightsj/RN_Demo |
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
TouchableHighlight
} from 'react-native';
export var FlAG_SETTINGITEMTYPE= {flag_top:'top',flag_middle:'middle',flag_bottom:'bottom',flag_single:'single'};
export default class ViewUtils{
//
static getLeftButton(callBack){
return <TouchableOpacity
style={{padding:8}}
onPress={callBack}>
<Image
style={{width:12,height:16,tintColor:'white'}}
source={{uri:'nav_back'}}
/>
</TouchableOpacity>
}
//用于for循环生成的cellItem
static createSettingItemWithIndex(index,settingItemType,callBack,icon,title,detailText,tintColor, arrowIcon,expandableIcon){
let topLineView = null;
let bottomLineView = null;
let topStyle = null;
if (settingItemType === FlAG_SETTINGITEMTYPE.flag_top || settingItemType === FlAG_SETTINGITEMTYPE.flag_single){
topStyle = {marginTop:10}
}else{
topStyle = {marginTop:0}
}
if (settingItemType === FlAG_SETTINGITEMTYPE.flag_top || settingItemType ===FlAG_SETTINGITEMTYPE.flag_single){
topLineView = <View style={styles.settingItemFullLineStyle}></View>
}
if (settingItemType === FlAG_SETTINGITEMTYPE.flag_bottom ||settingItemType === FlAG_SETTINGITEMTYPE.flag_single){
bottomLineView = <View style={styles.settingItemFullLineStyle}></View>
}else if (settingItemType === FlAG_SETTINGITEMTYPE.flag_top || settingItemType === FlAG_SETTINGITEMTYPE.flag_middle){
bottomLineView = <View style={styles.settingItemMiddleLineStyle}></View>
}
let image = null;
if (icon) {
image = <Image
source={{uri: icon}}
resizeMode='stretch'
style={[{width: 22, height: 22}]}
/>
}
let content = <View>
{topLineView}
<TouchableHighlight
onPress={callBack}
underlayColor= 'transparent'
>
<View style={styles.settingItemContainerStyle}>
{/*左侧*/}
<View style={{flexDirection:'row',alignItems:'center'}}>
{image}
<Text style={styles.settingItemTitleStyle}>{title}</Text>
</View>
{/*右侧*/}
<View style={{flexDirection:'row',alignItems:'center'}}>
<Text style={styles.settingItemDetailTitleStyle}>{detailText}</Text>
<Image source={{uri:expandableIcon?expandableIcon:arrowIcon}}
style={[{marginRight:6,height:12,width:8}]}
/>
</View>
</View>
</TouchableHighlight>
{bottomLineView}
</View>
if(index > 0 || index == 0){
return (
<View style={[{backgroundColor:'white'},topStyle]} key = {index}>
{content}
</View>
)
}else{
return (
<View style={[{backgroundColor:'white'},topStyle]}>
{content}
</View>
)
}
}
static createSettingItem(settingItemType,callBack,icon,title,detailText,tintColor, arrowIcon,expandableIcon){
return this.createSettingItemWithIndex(null,settingItemType,callBack,icon,title,detailText,tintColor, arrowIcon,expandableIcon )
}
static createMiddleContentItem(callBack,text){
return (
<View style={[{backgroundColor:'white'},{marginTop:10}]}>
<View style={styles.settingItemFullLineStyle}></View>
<TouchableHighlight
onPress={callBack}
underlayColor= 'transparent'>
<View style={styles.settingItemMiddleContainerStyle}>
<View style={{justifyContent:'center',alignItems:'center'}}>
<Text style={styles.settingMiddleTittleStyle}>{text}</Text>
</View>
</View>
</TouchableHighlight>
<View style={styles.settingItemFullLineStyle}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
settingItemContainerStyle:{
flexDirection:'row',
justifyContent:'space-between',
alignItems:'center',
padding:10,
height:44,
},
settingItemTitleStyle:{
marginLeft:12,
fontSize:16,
fontFamily:'Helvetica',
fontWeight:'100'
},
settingItemDetailTitleStyle:{
marginRight:12,
color:'gray',
fontSize:15,
fontFamily:'Helvetica',
fontWeight:'100'
},
settingItemMiddleContainerStyle:{
flexDirection:'row',
justifyContent:'center',
alignItems:'center',
padding:10,
height:44,
},
settingMiddleTittleStyle:{
fontSize:17,
justifyContent: 'center',
fontFamily:'Helvetica',
fontWeight:'100'
},
settingItemFullLineStyle:{
backgroundColor: '#D5D5D5',
height: 0.8,
},
settingItemMiddleLineStyle:{
backgroundColor: '#D5D5D5',
height: 0.8,
marginLeft:14,
marginRight:14
},
}); |
client/app/components/Footer/index.js | katharosada/bus-shaming | import React from 'react';
import { Link } from 'react-router-dom';
import './styles.less';
/**
* Footer component.
**/
export default function Header() {
return (
<footer id="main-footer">
<div className="column">
Made by <a href="https://katiebell.net">Katie Bell</a>
</div>
</footer>
);
};
|
local-cli/templates/HelloWorld/index.android.js | esauter5/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
src/components/User/Sprint/Views/Mobile/index.js | Ftornik/forwardteam.space | /**
* [IL]
* Library Import
*/
import React from 'react';
import cx from 'classnames';
/**
* [IS]
* Style Import
*/
import Styles from './Styles/main.scss';
import SprintImage from 'components/Assets/Pins/Sprint';
function Sprint(props) {
const { user, sprint } = props;
const sprintProgress = user.progress.sprints[sprint.id] ? user.progress.sprints[sprint.id] : null;
const percent = sprintProgress.amount;
const maxPercent = 94;
const maxRightOffset = 91;
const minPercent = 4;
const progressStyle = {
width: `${percent}%`
};
const percentStyle = {
left: `${percent}%`,
transform: percent > minPercent && percent < maxPercent ? 'translateX(-54%)' : null
};
if (percent >= maxPercent) {
percentStyle.left = `${maxRightOffset}%`;
} else if (percent <= minPercent) {
percentStyle.left = '0';
}
const spintReqs = sprint.requirements.map((req) => {
let reqDone = false;
let reqCount = 0;
if (sprintProgress[req.id]) {
if (req.count) {
reqCount = sprintProgress[req.id];
reqDone = req.count.total === sprintProgress[req.id];
} else {
reqDone = true;
}
}
const reqClass = cx({
[Styles.item]: true,
[Styles.active]: reqDone
});
const progress = req.count ? (
<span className={ Styles.progress }>{ req.count.title } { reqCount } / { req.count.total }</span>
) : null;
return (
<div className={ reqClass } key={ req.title }>
<p className={ Styles.text }>
{ req.title }
{ progress }
</p>
</div>
);
});
return (
<section className={ Styles.sprintComponent }>
<div className={ Styles.info }>
<span className={ Styles.sprintNumber }>{ sprint.subtitle }</span>
<h1 className={ Styles.title }>{ sprint.title }</h1>
<div className={ Styles.progressBlock }>
<div className={ Styles.progressBar }>
<div className={ Styles.progress } style={ progressStyle }>
<span className={ Styles.percent } style={ percentStyle }>
<label>{ percent }% </label>
</span>
</div>
</div>
</div>
<div className={ Styles.quests }>
<div className={ Styles.items }>
{ spintReqs }
</div>
</div>
</div>
<div className={ Styles.image }>
<SprintImage className={ Styles.icon }/>
</div>
</section>
);
}
/**
* [IE]
* Export
*/
export default Sprint;
|
wrappers/html.js | grand-crew/grand-crew.github.io | import React from 'react'
module.exports = React.createClass({
propTypes () {
return {
router: React.PropTypes.object,
}
},
render () {
const post = this.props.route.page.data
return (
<div className="markdown">
<h1 dangerouslySetInnerHTML={{ __html: post.title }} />
<div dangerouslySetInnerHTML={{ __html: post.body }} />
</div>
)
},
})
|
packages/material-ui-icons/src/AccessibilityTwoTone.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z" /></g></React.Fragment>
, 'AccessibilityTwoTone');
|
node_modules/yui/scrollview-base/scrollview-base-coverage.js | AllenHunn/aurelia-fetch-client-extensions | if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/scrollview-base/scrollview-base.js']) {
__coverage__['build/scrollview-base/scrollview-base.js'] = {"path":"build/scrollview-base/scrollview-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0,0],"52":[0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0,0,0,0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":27},"end":{"line":1,"column":46}}},"2":{"name":"(anonymous_2)","line":49,"loc":{"start":{"line":49,"column":17},"end":{"line":49,"column":42}}},"3":{"name":"ScrollView","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":22}}},"4":{"name":"(anonymous_4)","line":168,"loc":{"start":{"line":168,"column":17},"end":{"line":168,"column":29}}},"5":{"name":"(anonymous_5)","line":189,"loc":{"start":{"line":189,"column":12},"end":{"line":189,"column":24}}},"6":{"name":"(anonymous_6)","line":237,"loc":{"start":{"line":237,"column":16},"end":{"line":237,"column":28}}},"7":{"name":"(anonymous_7)","line":265,"loc":{"start":{"line":265,"column":15},"end":{"line":265,"column":31}}},"8":{"name":"(anonymous_8)","line":285,"loc":{"start":{"line":285,"column":16},"end":{"line":285,"column":33}}},"9":{"name":"(anonymous_9)","line":308,"loc":{"start":{"line":308,"column":21},"end":{"line":308,"column":43}}},"10":{"name":"(anonymous_10)","line":330,"loc":{"start":{"line":330,"column":12},"end":{"line":330,"column":24}}},"11":{"name":"(anonymous_11)","line":374,"loc":{"start":{"line":374,"column":20},"end":{"line":374,"column":32}}},"12":{"name":"(anonymous_12)","line":417,"loc":{"start":{"line":417,"column":25},"end":{"line":417,"column":37}}},"13":{"name":"(anonymous_13)","line":459,"loc":{"start":{"line":459,"column":16},"end":{"line":459,"column":34}}},"14":{"name":"(anonymous_14)","line":476,"loc":{"start":{"line":476,"column":16},"end":{"line":476,"column":28}}},"15":{"name":"(anonymous_15)","line":499,"loc":{"start":{"line":499,"column":14},"end":{"line":499,"column":54}}},"16":{"name":"(anonymous_16)","line":579,"loc":{"start":{"line":579,"column":16},"end":{"line":579,"column":32}}},"17":{"name":"(anonymous_17)","line":599,"loc":{"start":{"line":599,"column":14},"end":{"line":599,"column":35}}},"18":{"name":"(anonymous_18)","line":616,"loc":{"start":{"line":616,"column":17},"end":{"line":616,"column":29}}},"19":{"name":"(anonymous_19)","line":641,"loc":{"start":{"line":641,"column":25},"end":{"line":641,"column":38}}},"20":{"name":"(anonymous_20)","line":707,"loc":{"start":{"line":707,"column":20},"end":{"line":707,"column":33}}},"21":{"name":"(anonymous_21)","line":749,"loc":{"start":{"line":749,"column":23},"end":{"line":749,"column":36}}},"22":{"name":"(anonymous_22)","line":804,"loc":{"start":{"line":804,"column":12},"end":{"line":804,"column":25}}},"23":{"name":"(anonymous_23)","line":837,"loc":{"start":{"line":837,"column":17},"end":{"line":837,"column":63}}},"24":{"name":"(anonymous_24)","line":900,"loc":{"start":{"line":900,"column":18},"end":{"line":900,"column":30}}},"25":{"name":"(anonymous_25)","line":920,"loc":{"start":{"line":920,"column":17},"end":{"line":920,"column":30}}},"26":{"name":"(anonymous_26)","line":970,"loc":{"start":{"line":970,"column":20},"end":{"line":970,"column":36}}},"27":{"name":"(anonymous_27)","line":993,"loc":{"start":{"line":993,"column":15},"end":{"line":993,"column":27}}},"28":{"name":"(anonymous_28)","line":1025,"loc":{"start":{"line":1025,"column":24},"end":{"line":1025,"column":37}}},"29":{"name":"(anonymous_29)","line":1062,"loc":{"start":{"line":1062,"column":23},"end":{"line":1062,"column":36}}},"30":{"name":"(anonymous_30)","line":1073,"loc":{"start":{"line":1073,"column":26},"end":{"line":1073,"column":39}}},"31":{"name":"(anonymous_31)","line":1085,"loc":{"start":{"line":1085,"column":22},"end":{"line":1085,"column":35}}},"32":{"name":"(anonymous_32)","line":1096,"loc":{"start":{"line":1096,"column":22},"end":{"line":1096,"column":35}}},"33":{"name":"(anonymous_33)","line":1107,"loc":{"start":{"line":1107,"column":21},"end":{"line":1107,"column":33}}},"34":{"name":"(anonymous_34)","line":1118,"loc":{"start":{"line":1118,"column":21},"end":{"line":1118,"column":33}}},"35":{"name":"(anonymous_35)","line":1140,"loc":{"start":{"line":1140,"column":17},"end":{"line":1140,"column":32}}},"36":{"name":"(anonymous_36)","line":1161,"loc":{"start":{"line":1161,"column":17},"end":{"line":1161,"column":31}}},"37":{"name":"(anonymous_37)","line":1179,"loc":{"start":{"line":1179,"column":17},"end":{"line":1179,"column":31}}},"38":{"name":"(anonymous_38)","line":1191,"loc":{"start":{"line":1191,"column":17},"end":{"line":1191,"column":31}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1457,"column":110}},"2":{"start":{"line":11,"column":0},"end":{"line":51,"column":6}},"3":{"start":{"line":50,"column":8},"end":{"line":50,"column":49}},"4":{"start":{"line":62,"column":0},"end":{"line":64,"column":1}},"5":{"start":{"line":63,"column":4},"end":{"line":63,"column":61}},"6":{"start":{"line":66,"column":0},"end":{"line":1454,"column":3}},"7":{"start":{"line":169,"column":8},"end":{"line":169,"column":22}},"8":{"start":{"line":172,"column":8},"end":{"line":172,"column":38}},"9":{"start":{"line":173,"column":8},"end":{"line":173,"column":37}},"10":{"start":{"line":176,"column":8},"end":{"line":176,"column":33}},"11":{"start":{"line":177,"column":8},"end":{"line":177,"column":37}},"12":{"start":{"line":178,"column":8},"end":{"line":178,"column":48}},"13":{"start":{"line":179,"column":8},"end":{"line":179,"column":49}},"14":{"start":{"line":180,"column":8},"end":{"line":180,"column":52}},"15":{"start":{"line":190,"column":8},"end":{"line":190,"column":22}},"16":{"start":{"line":193,"column":8},"end":{"line":193,"column":37}},"17":{"start":{"line":194,"column":8},"end":{"line":194,"column":35}},"18":{"start":{"line":195,"column":8},"end":{"line":195,"column":33}},"19":{"start":{"line":198,"column":8},"end":{"line":198,"column":24}},"20":{"start":{"line":201,"column":8},"end":{"line":203,"column":9}},"21":{"start":{"line":202,"column":12},"end":{"line":202,"column":44}},"22":{"start":{"line":206,"column":8},"end":{"line":208,"column":9}},"23":{"start":{"line":207,"column":12},"end":{"line":207,"column":60}},"24":{"start":{"line":210,"column":8},"end":{"line":212,"column":9}},"25":{"start":{"line":211,"column":12},"end":{"line":211,"column":56}},"26":{"start":{"line":214,"column":8},"end":{"line":216,"column":9}},"27":{"start":{"line":215,"column":12},"end":{"line":215,"column":46}},"28":{"start":{"line":218,"column":8},"end":{"line":220,"column":9}},"29":{"start":{"line":219,"column":12},"end":{"line":219,"column":58}},"30":{"start":{"line":222,"column":8},"end":{"line":224,"column":9}},"31":{"start":{"line":223,"column":12},"end":{"line":223,"column":58}},"32":{"start":{"line":238,"column":8},"end":{"line":240,"column":50}},"33":{"start":{"line":243,"column":8},"end":{"line":253,"column":11}},"34":{"start":{"line":266,"column":8},"end":{"line":267,"column":24}},"35":{"start":{"line":270,"column":8},"end":{"line":270,"column":31}},"36":{"start":{"line":272,"column":8},"end":{"line":274,"column":9}},"37":{"start":{"line":273,"column":12},"end":{"line":273,"column":89}},"38":{"start":{"line":286,"column":8},"end":{"line":287,"column":24}},"39":{"start":{"line":290,"column":8},"end":{"line":290,"column":32}},"40":{"start":{"line":292,"column":8},"end":{"line":297,"column":9}},"41":{"start":{"line":293,"column":12},"end":{"line":293,"column":69}},"42":{"start":{"line":296,"column":12},"end":{"line":296,"column":39}},"43":{"start":{"line":309,"column":8},"end":{"line":310,"column":24}},"44":{"start":{"line":314,"column":8},"end":{"line":314,"column":37}},"45":{"start":{"line":317,"column":8},"end":{"line":320,"column":9}},"46":{"start":{"line":319,"column":12},"end":{"line":319,"column":71}},"47":{"start":{"line":331,"column":8},"end":{"line":336,"column":51}},"48":{"start":{"line":339,"column":8},"end":{"line":348,"column":9}},"49":{"start":{"line":342,"column":12},"end":{"line":345,"column":14}},"50":{"start":{"line":347,"column":12},"end":{"line":347,"column":37}},"51":{"start":{"line":351,"column":8},"end":{"line":351,"column":66}},"52":{"start":{"line":354,"column":8},"end":{"line":354,"column":41}},"53":{"start":{"line":357,"column":8},"end":{"line":357,"column":33}},"54":{"start":{"line":360,"column":8},"end":{"line":362,"column":9}},"55":{"start":{"line":361,"column":12},"end":{"line":361,"column":27}},"56":{"start":{"line":375,"column":8},"end":{"line":385,"column":17}},"57":{"start":{"line":388,"column":8},"end":{"line":391,"column":9}},"58":{"start":{"line":389,"column":12},"end":{"line":389,"column":46}},"59":{"start":{"line":390,"column":12},"end":{"line":390,"column":47}},"60":{"start":{"line":393,"column":8},"end":{"line":393,"column":48}},"61":{"start":{"line":394,"column":8},"end":{"line":394,"column":38}},"62":{"start":{"line":396,"column":8},"end":{"line":396,"column":29}},"63":{"start":{"line":397,"column":8},"end":{"line":402,"column":10}},"64":{"start":{"line":403,"column":8},"end":{"line":403,"column":43}},"65":{"start":{"line":405,"column":8},"end":{"line":405,"column":48}},"66":{"start":{"line":407,"column":8},"end":{"line":407,"column":20}},"67":{"start":{"line":418,"column":8},"end":{"line":430,"column":60}},"68":{"start":{"line":432,"column":8},"end":{"line":434,"column":9}},"69":{"start":{"line":433,"column":12},"end":{"line":433,"column":48}},"70":{"start":{"line":436,"column":8},"end":{"line":438,"column":9}},"71":{"start":{"line":437,"column":12},"end":{"line":437,"column":46}},"72":{"start":{"line":440,"column":8},"end":{"line":445,"column":11}},"73":{"start":{"line":460,"column":8},"end":{"line":460,"column":22}},"74":{"start":{"line":464,"column":8},"end":{"line":464,"column":43}},"75":{"start":{"line":465,"column":8},"end":{"line":465,"column":43}},"76":{"start":{"line":466,"column":8},"end":{"line":466,"column":43}},"77":{"start":{"line":467,"column":8},"end":{"line":467,"column":43}},"78":{"start":{"line":477,"column":8},"end":{"line":477,"column":22}},"79":{"start":{"line":479,"column":8},"end":{"line":484,"column":10}},"80":{"start":{"line":501,"column":8},"end":{"line":503,"column":9}},"81":{"start":{"line":502,"column":12},"end":{"line":502,"column":19}},"82":{"start":{"line":505,"column":8},"end":{"line":512,"column":22}},"83":{"start":{"line":515,"column":8},"end":{"line":515,"column":33}},"84":{"start":{"line":516,"column":8},"end":{"line":516,"column":42}},"85":{"start":{"line":517,"column":8},"end":{"line":517,"column":26}},"86":{"start":{"line":519,"column":8},"end":{"line":522,"column":9}},"87":{"start":{"line":520,"column":12},"end":{"line":520,"column":42}},"88":{"start":{"line":521,"column":12},"end":{"line":521,"column":24}},"89":{"start":{"line":524,"column":8},"end":{"line":527,"column":9}},"90":{"start":{"line":525,"column":12},"end":{"line":525,"column":42}},"91":{"start":{"line":526,"column":12},"end":{"line":526,"column":24}},"92":{"start":{"line":529,"column":8},"end":{"line":529,"column":46}},"93":{"start":{"line":531,"column":8},"end":{"line":534,"column":9}},"94":{"start":{"line":533,"column":12},"end":{"line":533,"column":80}},"95":{"start":{"line":537,"column":8},"end":{"line":567,"column":9}},"96":{"start":{"line":538,"column":12},"end":{"line":550,"column":13}},"97":{"start":{"line":539,"column":16},"end":{"line":539,"column":54}},"98":{"start":{"line":544,"column":16},"end":{"line":546,"column":17}},"99":{"start":{"line":545,"column":20},"end":{"line":545,"column":51}},"100":{"start":{"line":547,"column":16},"end":{"line":549,"column":17}},"101":{"start":{"line":548,"column":20},"end":{"line":548,"column":50}},"102":{"start":{"line":555,"column":12},"end":{"line":555,"column":39}},"103":{"start":{"line":556,"column":12},"end":{"line":556,"column":50}},"104":{"start":{"line":558,"column":12},"end":{"line":564,"column":13}},"105":{"start":{"line":559,"column":16},"end":{"line":559,"column":49}},"106":{"start":{"line":562,"column":16},"end":{"line":562,"column":44}},"107":{"start":{"line":563,"column":16},"end":{"line":563,"column":43}},"108":{"start":{"line":566,"column":12},"end":{"line":566,"column":50}},"109":{"start":{"line":581,"column":8},"end":{"line":581,"column":57}},"110":{"start":{"line":583,"column":8},"end":{"line":585,"column":9}},"111":{"start":{"line":584,"column":12},"end":{"line":584,"column":37}},"112":{"start":{"line":587,"column":8},"end":{"line":587,"column":20}},"113":{"start":{"line":600,"column":8},"end":{"line":605,"column":9}},"114":{"start":{"line":601,"column":12},"end":{"line":601,"column":62}},"115":{"start":{"line":603,"column":12},"end":{"line":603,"column":40}},"116":{"start":{"line":604,"column":12},"end":{"line":604,"column":39}},"117":{"start":{"line":617,"column":8},"end":{"line":617,"column":22}},"118":{"start":{"line":620,"column":8},"end":{"line":631,"column":9}},"119":{"start":{"line":621,"column":12},"end":{"line":621,"column":27}},"120":{"start":{"line":630,"column":12},"end":{"line":630,"column":35}},"121":{"start":{"line":643,"column":8},"end":{"line":645,"column":9}},"122":{"start":{"line":644,"column":12},"end":{"line":644,"column":25}},"123":{"start":{"line":647,"column":8},"end":{"line":652,"column":32}},"124":{"start":{"line":654,"column":8},"end":{"line":656,"column":9}},"125":{"start":{"line":655,"column":12},"end":{"line":655,"column":31}},"126":{"start":{"line":659,"column":8},"end":{"line":662,"column":9}},"127":{"start":{"line":660,"column":12},"end":{"line":660,"column":30}},"128":{"start":{"line":661,"column":12},"end":{"line":661,"column":29}},"129":{"start":{"line":665,"column":8},"end":{"line":665,"column":31}},"130":{"start":{"line":668,"column":8},"end":{"line":697,"column":10}},"131":{"start":{"line":708,"column":8},"end":{"line":718,"column":32}},"132":{"start":{"line":720,"column":8},"end":{"line":722,"column":9}},"133":{"start":{"line":721,"column":12},"end":{"line":721,"column":31}},"134":{"start":{"line":724,"column":8},"end":{"line":724,"column":48}},"135":{"start":{"line":725,"column":8},"end":{"line":725,"column":48}},"136":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"137":{"start":{"line":730,"column":12},"end":{"line":730,"column":97}},"138":{"start":{"line":734,"column":8},"end":{"line":739,"column":9}},"139":{"start":{"line":735,"column":12},"end":{"line":735,"column":54}},"140":{"start":{"line":737,"column":13},"end":{"line":739,"column":9}},"141":{"start":{"line":738,"column":12},"end":{"line":738,"column":54}},"142":{"start":{"line":750,"column":8},"end":{"line":755,"column":18}},"143":{"start":{"line":757,"column":8},"end":{"line":759,"column":9}},"144":{"start":{"line":758,"column":12},"end":{"line":758,"column":31}},"145":{"start":{"line":762,"column":8},"end":{"line":762,"column":37}},"146":{"start":{"line":763,"column":8},"end":{"line":763,"column":37}},"147":{"start":{"line":766,"column":8},"end":{"line":766,"column":39}},"148":{"start":{"line":767,"column":8},"end":{"line":767,"column":42}},"149":{"start":{"line":770,"column":8},"end":{"line":794,"column":9}},"150":{"start":{"line":776,"column":12},"end":{"line":793,"column":13}},"151":{"start":{"line":778,"column":16},"end":{"line":778,"column":44}},"152":{"start":{"line":781,"column":16},"end":{"line":792,"column":17}},"153":{"start":{"line":782,"column":20},"end":{"line":782,"column":35}},"154":{"start":{"line":789,"column":20},"end":{"line":791,"column":21}},"155":{"start":{"line":790,"column":24},"end":{"line":790,"column":41}},"156":{"start":{"line":805,"column":8},"end":{"line":807,"column":9}},"157":{"start":{"line":806,"column":12},"end":{"line":806,"column":25}},"158":{"start":{"line":809,"column":8},"end":{"line":815,"column":45}},"159":{"start":{"line":818,"column":8},"end":{"line":820,"column":9}},"160":{"start":{"line":819,"column":12},"end":{"line":819,"column":38}},"161":{"start":{"line":823,"column":8},"end":{"line":825,"column":9}},"162":{"start":{"line":824,"column":12},"end":{"line":824,"column":68}},"163":{"start":{"line":839,"column":8},"end":{"line":864,"column":20}},"164":{"start":{"line":867,"column":8},"end":{"line":869,"column":9}},"165":{"start":{"line":868,"column":12},"end":{"line":868,"column":34}},"166":{"start":{"line":872,"column":8},"end":{"line":872,"column":61}},"167":{"start":{"line":875,"column":8},"end":{"line":897,"column":9}},"168":{"start":{"line":877,"column":12},"end":{"line":879,"column":13}},"169":{"start":{"line":878,"column":16},"end":{"line":878,"column":34}},"170":{"start":{"line":882,"column":12},"end":{"line":889,"column":13}},"171":{"start":{"line":883,"column":16},"end":{"line":883,"column":33}},"172":{"start":{"line":888,"column":16},"end":{"line":888,"column":31}},"173":{"start":{"line":895,"column":12},"end":{"line":895,"column":109}},"174":{"start":{"line":896,"column":12},"end":{"line":896,"column":42}},"175":{"start":{"line":901,"column":8},"end":{"line":901,"column":22}},"176":{"start":{"line":903,"column":8},"end":{"line":909,"column":9}},"177":{"start":{"line":905,"column":12},"end":{"line":905,"column":35}},"178":{"start":{"line":908,"column":12},"end":{"line":908,"column":33}},"179":{"start":{"line":921,"column":8},"end":{"line":927,"column":72}},"180":{"start":{"line":929,"column":8},"end":{"line":929,"column":80}},"181":{"start":{"line":935,"column":8},"end":{"line":958,"column":9}},"182":{"start":{"line":938,"column":12},"end":{"line":938,"column":35}},"183":{"start":{"line":941,"column":12},"end":{"line":941,"column":40}},"184":{"start":{"line":945,"column":12},"end":{"line":951,"column":13}},"185":{"start":{"line":947,"column":16},"end":{"line":947,"column":40}},"186":{"start":{"line":948,"column":16},"end":{"line":948,"column":38}},"187":{"start":{"line":954,"column":12},"end":{"line":954,"column":29}},"188":{"start":{"line":957,"column":12},"end":{"line":957,"column":31}},"189":{"start":{"line":971,"column":8},"end":{"line":981,"column":37}},"190":{"start":{"line":983,"column":8},"end":{"line":983,"column":118}},"191":{"start":{"line":994,"column":8},"end":{"line":1005,"column":41}},"192":{"start":{"line":1007,"column":8},"end":{"line":1015,"column":9}},"193":{"start":{"line":1008,"column":12},"end":{"line":1008,"column":71}},"194":{"start":{"line":1010,"column":13},"end":{"line":1015,"column":9}},"195":{"start":{"line":1011,"column":12},"end":{"line":1011,"column":71}},"196":{"start":{"line":1014,"column":12},"end":{"line":1014,"column":29}},"197":{"start":{"line":1026,"column":8},"end":{"line":1028,"column":9}},"198":{"start":{"line":1027,"column":12},"end":{"line":1027,"column":25}},"199":{"start":{"line":1030,"column":8},"end":{"line":1034,"column":30}},"200":{"start":{"line":1037,"column":8},"end":{"line":1037,"column":73}},"201":{"start":{"line":1040,"column":8},"end":{"line":1047,"column":9}},"202":{"start":{"line":1041,"column":12},"end":{"line":1041,"column":35}},"203":{"start":{"line":1042,"column":12},"end":{"line":1042,"column":48}},"204":{"start":{"line":1045,"column":12},"end":{"line":1045,"column":48}},"205":{"start":{"line":1046,"column":12},"end":{"line":1046,"column":35}},"206":{"start":{"line":1049,"column":8},"end":{"line":1049,"column":36}},"207":{"start":{"line":1050,"column":8},"end":{"line":1050,"column":34}},"208":{"start":{"line":1052,"column":8},"end":{"line":1052,"column":44}},"209":{"start":{"line":1063,"column":8},"end":{"line":1063,"column":34}},"210":{"start":{"line":1075,"column":8},"end":{"line":1075,"column":35}},"211":{"start":{"line":1086,"column":8},"end":{"line":1086,"column":31}},"212":{"start":{"line":1097,"column":8},"end":{"line":1097,"column":33}},"213":{"start":{"line":1108,"column":8},"end":{"line":1108,"column":35}},"214":{"start":{"line":1119,"column":8},"end":{"line":1119,"column":22}},"215":{"start":{"line":1121,"column":8},"end":{"line":1123,"column":9}},"216":{"start":{"line":1122,"column":12},"end":{"line":1122,"column":30}},"217":{"start":{"line":1143,"column":8},"end":{"line":1148,"column":9}},"218":{"start":{"line":1144,"column":12},"end":{"line":1147,"column":14}},"219":{"start":{"line":1164,"column":8},"end":{"line":1166,"column":9}},"220":{"start":{"line":1165,"column":12},"end":{"line":1165,"column":44}},"221":{"start":{"line":1168,"column":8},"end":{"line":1168,"column":19}},"222":{"start":{"line":1180,"column":8},"end":{"line":1180,"column":43}},"223":{"start":{"line":1192,"column":8},"end":{"line":1192,"column":43}}},"branchMap":{"1":{"line":78,"type":"cond-expr","locations":[{"start":{"line":78,"column":38},"end":{"line":78,"column":42}},{"start":{"line":78,"column":45},"end":{"line":78,"column":50}}]},"2":{"line":201,"type":"if","locations":[{"start":{"line":201,"column":8},"end":{"line":201,"column":8}},{"start":{"line":201,"column":8},"end":{"line":201,"column":8}}]},"3":{"line":206,"type":"if","locations":[{"start":{"line":206,"column":8},"end":{"line":206,"column":8}},{"start":{"line":206,"column":8},"end":{"line":206,"column":8}}]},"4":{"line":210,"type":"if","locations":[{"start":{"line":210,"column":8},"end":{"line":210,"column":8}},{"start":{"line":210,"column":8},"end":{"line":210,"column":8}}]},"5":{"line":214,"type":"if","locations":[{"start":{"line":214,"column":8},"end":{"line":214,"column":8}},{"start":{"line":214,"column":8},"end":{"line":214,"column":8}}]},"6":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":8},"end":{"line":218,"column":8}},{"start":{"line":218,"column":8},"end":{"line":218,"column":8}}]},"7":{"line":222,"type":"if","locations":[{"start":{"line":222,"column":8},"end":{"line":222,"column":8}},{"start":{"line":222,"column":8},"end":{"line":222,"column":8}}]},"8":{"line":272,"type":"if","locations":[{"start":{"line":272,"column":8},"end":{"line":272,"column":8}},{"start":{"line":272,"column":8},"end":{"line":272,"column":8}}]},"9":{"line":292,"type":"if","locations":[{"start":{"line":292,"column":8},"end":{"line":292,"column":8}},{"start":{"line":292,"column":8},"end":{"line":292,"column":8}}]},"10":{"line":317,"type":"if","locations":[{"start":{"line":317,"column":8},"end":{"line":317,"column":8}},{"start":{"line":317,"column":8},"end":{"line":317,"column":8}}]},"11":{"line":339,"type":"if","locations":[{"start":{"line":339,"column":8},"end":{"line":339,"column":8}},{"start":{"line":339,"column":8},"end":{"line":339,"column":8}}]},"12":{"line":360,"type":"if","locations":[{"start":{"line":360,"column":8},"end":{"line":360,"column":8}},{"start":{"line":360,"column":8},"end":{"line":360,"column":8}}]},"13":{"line":388,"type":"if","locations":[{"start":{"line":388,"column":8},"end":{"line":388,"column":8}},{"start":{"line":388,"column":8},"end":{"line":388,"column":8}}]},"14":{"line":427,"type":"cond-expr","locations":[{"start":{"line":427,"column":32},"end":{"line":427,"column":67}},{"start":{"line":427,"column":70},"end":{"line":427,"column":71}}]},"15":{"line":428,"type":"cond-expr","locations":[{"start":{"line":428,"column":32},"end":{"line":428,"column":33}},{"start":{"line":428,"column":36},"end":{"line":428,"column":68}}]},"16":{"line":432,"type":"if","locations":[{"start":{"line":432,"column":8},"end":{"line":432,"column":8}},{"start":{"line":432,"column":8},"end":{"line":432,"column":8}}]},"17":{"line":432,"type":"binary-expr","locations":[{"start":{"line":432,"column":12},"end":{"line":432,"column":18}},{"start":{"line":432,"column":22},"end":{"line":432,"column":30}}]},"18":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":8},"end":{"line":436,"column":8}},{"start":{"line":436,"column":8},"end":{"line":436,"column":8}}]},"19":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":18}},{"start":{"line":436,"column":22},"end":{"line":436,"column":30}}]},"20":{"line":501,"type":"if","locations":[{"start":{"line":501,"column":8},"end":{"line":501,"column":8}},{"start":{"line":501,"column":8},"end":{"line":501,"column":8}}]},"21":{"line":515,"type":"binary-expr","locations":[{"start":{"line":515,"column":19},"end":{"line":515,"column":27}},{"start":{"line":515,"column":31},"end":{"line":515,"column":32}}]},"22":{"line":516,"type":"binary-expr","locations":[{"start":{"line":516,"column":17},"end":{"line":516,"column":23}},{"start":{"line":516,"column":27},"end":{"line":516,"column":41}}]},"23":{"line":517,"type":"binary-expr","locations":[{"start":{"line":517,"column":15},"end":{"line":517,"column":19}},{"start":{"line":517,"column":23},"end":{"line":517,"column":25}}]},"24":{"line":519,"type":"if","locations":[{"start":{"line":519,"column":8},"end":{"line":519,"column":8}},{"start":{"line":519,"column":8},"end":{"line":519,"column":8}}]},"25":{"line":524,"type":"if","locations":[{"start":{"line":524,"column":8},"end":{"line":524,"column":8}},{"start":{"line":524,"column":8},"end":{"line":524,"column":8}}]},"26":{"line":531,"type":"if","locations":[{"start":{"line":531,"column":8},"end":{"line":531,"column":8}},{"start":{"line":531,"column":8},"end":{"line":531,"column":8}}]},"27":{"line":537,"type":"if","locations":[{"start":{"line":537,"column":8},"end":{"line":537,"column":8}},{"start":{"line":537,"column":8},"end":{"line":537,"column":8}}]},"28":{"line":538,"type":"if","locations":[{"start":{"line":538,"column":12},"end":{"line":538,"column":12}},{"start":{"line":538,"column":12},"end":{"line":538,"column":12}}]},"29":{"line":544,"type":"if","locations":[{"start":{"line":544,"column":16},"end":{"line":544,"column":16}},{"start":{"line":544,"column":16},"end":{"line":544,"column":16}}]},"30":{"line":547,"type":"if","locations":[{"start":{"line":547,"column":16},"end":{"line":547,"column":16}},{"start":{"line":547,"column":16},"end":{"line":547,"column":16}}]},"31":{"line":558,"type":"if","locations":[{"start":{"line":558,"column":12},"end":{"line":558,"column":12}},{"start":{"line":558,"column":12},"end":{"line":558,"column":12}}]},"32":{"line":583,"type":"if","locations":[{"start":{"line":583,"column":8},"end":{"line":583,"column":8}},{"start":{"line":583,"column":8},"end":{"line":583,"column":8}}]},"33":{"line":600,"type":"if","locations":[{"start":{"line":600,"column":8},"end":{"line":600,"column":8}},{"start":{"line":600,"column":8},"end":{"line":600,"column":8}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":643,"type":"if","locations":[{"start":{"line":643,"column":8},"end":{"line":643,"column":8}},{"start":{"line":643,"column":8},"end":{"line":643,"column":8}}]},"36":{"line":654,"type":"if","locations":[{"start":{"line":654,"column":8},"end":{"line":654,"column":8}},{"start":{"line":654,"column":8},"end":{"line":654,"column":8}}]},"37":{"line":659,"type":"if","locations":[{"start":{"line":659,"column":8},"end":{"line":659,"column":8}},{"start":{"line":659,"column":8},"end":{"line":659,"column":8}}]},"38":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":8},"end":{"line":720,"column":8}},{"start":{"line":720,"column":8},"end":{"line":720,"column":8}}]},"39":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"40":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":83},"end":{"line":730,"column":88}},{"start":{"line":730,"column":91},"end":{"line":730,"column":96}}]},"41":{"line":734,"type":"if","locations":[{"start":{"line":734,"column":8},"end":{"line":734,"column":8}},{"start":{"line":734,"column":8},"end":{"line":734,"column":8}}]},"42":{"line":734,"type":"binary-expr","locations":[{"start":{"line":734,"column":12},"end":{"line":734,"column":34}},{"start":{"line":734,"column":38},"end":{"line":734,"column":45}}]},"43":{"line":737,"type":"if","locations":[{"start":{"line":737,"column":13},"end":{"line":737,"column":13}},{"start":{"line":737,"column":13},"end":{"line":737,"column":13}}]},"44":{"line":737,"type":"binary-expr","locations":[{"start":{"line":737,"column":17},"end":{"line":737,"column":39}},{"start":{"line":737,"column":43},"end":{"line":737,"column":50}}]},"45":{"line":757,"type":"if","locations":[{"start":{"line":757,"column":8},"end":{"line":757,"column":8}},{"start":{"line":757,"column":8},"end":{"line":757,"column":8}}]},"46":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"47":{"line":776,"type":"if","locations":[{"start":{"line":776,"column":12},"end":{"line":776,"column":12}},{"start":{"line":776,"column":12},"end":{"line":776,"column":12}}]},"48":{"line":776,"type":"binary-expr","locations":[{"start":{"line":776,"column":16},"end":{"line":776,"column":39}},{"start":{"line":776,"column":43},"end":{"line":776,"column":66}}]},"49":{"line":781,"type":"if","locations":[{"start":{"line":781,"column":16},"end":{"line":781,"column":16}},{"start":{"line":781,"column":16},"end":{"line":781,"column":16}}]},"50":{"line":789,"type":"if","locations":[{"start":{"line":789,"column":20},"end":{"line":789,"column":20}},{"start":{"line":789,"column":20},"end":{"line":789,"column":20}}]},"51":{"line":789,"type":"binary-expr","locations":[{"start":{"line":789,"column":24},"end":{"line":789,"column":33}},{"start":{"line":789,"column":38},"end":{"line":789,"column":46}},{"start":{"line":789,"column":50},"end":{"line":789,"column":83}}]},"52":{"line":805,"type":"if","locations":[{"start":{"line":805,"column":8},"end":{"line":805,"column":8}},{"start":{"line":805,"column":8},"end":{"line":805,"column":8}}]},"53":{"line":814,"type":"cond-expr","locations":[{"start":{"line":814,"column":45},"end":{"line":814,"column":53}},{"start":{"line":814,"column":56},"end":{"line":814,"column":64}}]},"54":{"line":818,"type":"if","locations":[{"start":{"line":818,"column":8},"end":{"line":818,"column":8}},{"start":{"line":818,"column":8},"end":{"line":818,"column":8}}]},"55":{"line":823,"type":"if","locations":[{"start":{"line":823,"column":8},"end":{"line":823,"column":8}},{"start":{"line":823,"column":8},"end":{"line":823,"column":8}}]},"56":{"line":840,"type":"cond-expr","locations":[{"start":{"line":840,"column":45},"end":{"line":840,"column":53}},{"start":{"line":840,"column":56},"end":{"line":840,"column":64}}]},"57":{"line":854,"type":"cond-expr","locations":[{"start":{"line":854,"column":40},"end":{"line":854,"column":57}},{"start":{"line":854,"column":60},"end":{"line":854,"column":77}}]},"58":{"line":855,"type":"cond-expr","locations":[{"start":{"line":855,"column":40},"end":{"line":855,"column":57}},{"start":{"line":855,"column":60},"end":{"line":855,"column":77}}]},"59":{"line":861,"type":"binary-expr","locations":[{"start":{"line":861,"column":30},"end":{"line":861,"column":38}},{"start":{"line":861,"column":43},"end":{"line":861,"column":76}}]},"60":{"line":862,"type":"binary-expr","locations":[{"start":{"line":862,"column":30},"end":{"line":862,"column":38}},{"start":{"line":862,"column":43},"end":{"line":862,"column":76}}]},"61":{"line":867,"type":"if","locations":[{"start":{"line":867,"column":8},"end":{"line":867,"column":8}},{"start":{"line":867,"column":8},"end":{"line":867,"column":8}}]},"62":{"line":867,"type":"binary-expr","locations":[{"start":{"line":867,"column":12},"end":{"line":867,"column":26}},{"start":{"line":867,"column":30},"end":{"line":867,"column":44}}]},"63":{"line":875,"type":"if","locations":[{"start":{"line":875,"column":8},"end":{"line":875,"column":8}},{"start":{"line":875,"column":8},"end":{"line":875,"column":8}}]},"64":{"line":875,"type":"binary-expr","locations":[{"start":{"line":875,"column":12},"end":{"line":875,"column":19}},{"start":{"line":875,"column":23},"end":{"line":875,"column":36}},{"start":{"line":875,"column":40},"end":{"line":875,"column":53}}]},"65":{"line":877,"type":"if","locations":[{"start":{"line":877,"column":12},"end":{"line":877,"column":12}},{"start":{"line":877,"column":12},"end":{"line":877,"column":12}}]},"66":{"line":882,"type":"if","locations":[{"start":{"line":882,"column":12},"end":{"line":882,"column":12}},{"start":{"line":882,"column":12},"end":{"line":882,"column":12}}]},"67":{"line":882,"type":"binary-expr","locations":[{"start":{"line":882,"column":16},"end":{"line":882,"column":24}},{"start":{"line":882,"column":28},"end":{"line":882,"column":36}}]},"68":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"69":{"line":927,"type":"cond-expr","locations":[{"start":{"line":927,"column":48},"end":{"line":927,"column":49}},{"start":{"line":927,"column":52},"end":{"line":927,"column":54}}]},"70":{"line":935,"type":"if","locations":[{"start":{"line":935,"column":8},"end":{"line":935,"column":8}},{"start":{"line":935,"column":8},"end":{"line":935,"column":8}}]},"71":{"line":935,"type":"binary-expr","locations":[{"start":{"line":935,"column":12},"end":{"line":935,"column":33}},{"start":{"line":935,"column":37},"end":{"line":935,"column":53}}]},"72":{"line":945,"type":"if","locations":[{"start":{"line":945,"column":12},"end":{"line":945,"column":12}},{"start":{"line":945,"column":12},"end":{"line":945,"column":12}}]},"73":{"line":975,"type":"binary-expr","locations":[{"start":{"line":975,"column":23},"end":{"line":975,"column":24}},{"start":{"line":975,"column":28},"end":{"line":975,"column":44}}]},"74":{"line":976,"type":"binary-expr","locations":[{"start":{"line":976,"column":23},"end":{"line":976,"column":24}},{"start":{"line":976,"column":28},"end":{"line":976,"column":44}}]},"75":{"line":983,"type":"binary-expr","locations":[{"start":{"line":983,"column":16},"end":{"line":983,"column":23}},{"start":{"line":983,"column":28},"end":{"line":983,"column":43}},{"start":{"line":983,"column":47},"end":{"line":983,"column":62}},{"start":{"line":983,"column":69},"end":{"line":983,"column":76}},{"start":{"line":983,"column":81},"end":{"line":983,"column":96}},{"start":{"line":983,"column":100},"end":{"line":983,"column":115}}]},"76":{"line":1007,"type":"if","locations":[{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}},{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}}]},"77":{"line":1010,"type":"if","locations":[{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}},{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}}]},"78":{"line":1026,"type":"if","locations":[{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}},{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}}]},"79":{"line":1040,"type":"if","locations":[{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}},{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}}]},"80":{"line":1121,"type":"if","locations":[{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}},{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}}]},"81":{"line":1143,"type":"if","locations":[{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}},{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}}]},"82":{"line":1145,"type":"cond-expr","locations":[{"start":{"line":1145,"column":37},"end":{"line":1145,"column":41}},{"start":{"line":1145,"column":44},"end":{"line":1145,"column":49}}]},"83":{"line":1146,"type":"cond-expr","locations":[{"start":{"line":1146,"column":37},"end":{"line":1146,"column":41}},{"start":{"line":1146,"column":44},"end":{"line":1146,"column":49}}]},"84":{"line":1164,"type":"if","locations":[{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}},{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}}]},"85":{"line":1393,"type":"cond-expr","locations":[{"start":{"line":1393,"column":34},"end":{"line":1393,"column":69}},{"start":{"line":1393,"column":72},"end":{"line":1393,"column":92}}]},"86":{"line":1394,"type":"cond-expr","locations":[{"start":{"line":1394,"column":34},"end":{"line":1394,"column":69}},{"start":{"line":1394,"column":72},"end":{"line":1394,"column":92}}]}},"code":["(function () { YUI.add('scrollview-base', function (Y, NAME) {","","/**"," * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators"," *"," * @module scrollview"," * @submodule scrollview-base"," */",""," // Local vars","var getClassName = Y.ClassNameManager.getClassName,"," DOCUMENT = Y.config.doc,"," IE = Y.UA.ie,"," NATIVE_TRANSITIONS = Y.Transition.useNative,"," vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated"," SCROLLVIEW = 'scrollview',"," CLASS_NAMES = {"," vertical: getClassName(SCROLLVIEW, 'vert'),"," horizontal: getClassName(SCROLLVIEW, 'horiz')"," },"," EV_SCROLL_END = 'scrollEnd',"," FLICK = 'flick',"," DRAG = 'drag',"," MOUSEWHEEL = 'mousewheel',"," UI = 'ui',"," TOP = 'top',"," LEFT = 'left',"," PX = 'px',"," AXIS = 'axis',"," SCROLL_Y = 'scrollY',"," SCROLL_X = 'scrollX',"," BOUNCE = 'bounce',"," DISABLED = 'disabled',"," DECELERATION = 'deceleration',"," DIM_X = 'x',"," DIM_Y = 'y',"," BOUNDING_BOX = 'boundingBox',"," CONTENT_BOX = 'contentBox',"," GESTURE_MOVE = 'gesturemove',"," START = 'start',"," END = 'end',"," EMPTY = '',"," ZERO = '0s',"," SNAP_DURATION = 'snapDuration',"," SNAP_EASING = 'snapEasing',"," EASING = 'easing',"," FRAME_DURATION = 'frameDuration',"," BOUNCE_RANGE = 'bounceRange',"," _constrain = function (val, min, max) {"," return Math.min(Math.max(val, min), max);"," };","","/**"," * ScrollView provides a scrollable widget, supporting flick gestures,"," * across both touch and mouse based devices."," *"," * @class ScrollView"," * @param config {Object} Object literal with initial attribute values"," * @extends Widget"," * @constructor"," */","function ScrollView() {"," ScrollView.superclass.constructor.apply(this, arguments);","}","","Y.ScrollView = Y.extend(ScrollView, Y.Widget, {",""," // *** Y.ScrollView prototype",""," /**"," * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit."," * Used by the _transform method."," *"," * @property _forceHWTransforms"," * @type boolean"," * @protected"," */"," _forceHWTransforms: Y.UA.webkit ? true : false,",""," /**"," * <p>Used to control whether or not ScrollView's internal"," * gesturemovestart, gesturemove and gesturemoveend"," * event listeners should preventDefault. The value is an"," * object, with \"start\", \"move\" and \"end\" properties used to"," * specify which events should preventDefault and which shouldn't:</p>"," *"," * <pre>"," * {"," * start: false,"," * move: true,"," * end: false"," * }"," * </pre>"," *"," * <p>The default values are set up in order to prevent panning,"," * on touch devices, while allowing click listeners on elements inside"," * the ScrollView to be notified as expected.</p>"," *"," * @property _prevent"," * @type Object"," * @protected"," */"," _prevent: {"," start: false,"," move: true,"," end: false"," },",""," /**"," * Contains the distance (postive or negative) in pixels by which"," * the scrollview was last scrolled. This is useful when setting up"," * click listeners on the scrollview content, which on mouse based"," * devices are always fired, even after a drag/flick."," *"," * <p>Touch based devices don't currently fire a click event,"," * if the finger has been moved (beyond a threshold) so this"," * check isn't required, if working in a purely touch based environment</p>"," *"," * @property lastScrolledAmt"," * @type Number"," * @public"," * @default 0"," */"," lastScrolledAmt: 0,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis"," *"," * @property _minScrollX"," * @type number"," * @protected"," */"," _minScrollX: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis"," *"," * @property _maxScrollX"," * @type number"," * @protected"," */"," _maxScrollX: null,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _minScrollY"," * @type number"," * @protected"," */"," _minScrollY: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _maxScrollY"," * @type number"," * @protected"," */"," _maxScrollY: null,",""," /**"," * Designated initializer"," *"," * @method initializer"," * @param {config} Configuration object for the plugin"," */"," initializer: function () {"," var sv = this;",""," // Cache these values, since they aren't going to change."," sv._bb = sv.get(BOUNDING_BOX);"," sv._cb = sv.get(CONTENT_BOX);",""," // Cache some attributes"," sv._cAxis = sv.get(AXIS);"," sv._cBounce = sv.get(BOUNCE);"," sv._cBounceRange = sv.get(BOUNCE_RANGE);"," sv._cDeceleration = sv.get(DECELERATION);"," sv._cFrameDuration = sv.get(FRAME_DURATION);"," },",""," /**"," * bindUI implementation"," *"," * Hooks up events for the widget"," * @method bindUI"," */"," bindUI: function () {"," var sv = this;",""," // Bind interaction listers"," sv._bindFlick(sv.get(FLICK));"," sv._bindDrag(sv.get(DRAG));"," sv._bindMousewheel(true);",""," // Bind change events"," sv._bindAttrs();",""," // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release."," if (IE) {"," sv._fixIESelect(sv._bb, sv._cb);"," }",""," // Set any deprecated static properties"," if (ScrollView.SNAP_DURATION) {"," sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);"," }",""," if (ScrollView.SNAP_EASING) {"," sv.set(SNAP_EASING, ScrollView.SNAP_EASING);"," }",""," if (ScrollView.EASING) {"," sv.set(EASING, ScrollView.EASING);"," }",""," if (ScrollView.FRAME_STEP) {"," sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);"," }",""," if (ScrollView.BOUNCE_RANGE) {"," sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);"," }",""," // Recalculate dimension properties"," // TODO: This should be throttled."," // Y.one(WINDOW).after('resize', sv._afterDimChange, sv);"," },",""," /**"," * Bind event listeners"," *"," * @method _bindAttrs"," * @private"," */"," _bindAttrs: function () {"," var sv = this,"," scrollChangeHandler = sv._afterScrollChange,"," dimChangeHandler = sv._afterDimChange;",""," // Bind any change event listeners"," sv.after({"," 'scrollEnd': sv._afterScrollEnd,"," 'disabledChange': sv._afterDisabledChange,"," 'flickChange': sv._afterFlickChange,"," 'dragChange': sv._afterDragChange,"," 'axisChange': sv._afterAxisChange,"," 'scrollYChange': scrollChangeHandler,"," 'scrollXChange': scrollChangeHandler,"," 'heightChange': dimChangeHandler,"," 'widthChange': dimChangeHandler"," });"," },",""," /**"," * Bind (or unbind) gesture move listeners required for drag support"," *"," * @method _bindDrag"," * @param drag {boolean} If true, the method binds listener to enable"," * drag (gesturemovestart). If false, the method unbinds gesturemove"," * listeners for drag support."," * @private"," */"," _bindDrag: function (drag) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'drag' listeners"," bb.detach(DRAG + '|*');",""," if (drag) {"," bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));"," }"," },",""," /**"," * Bind (or unbind) flick listeners."," *"," * @method _bindFlick"," * @param flick {Object|boolean} If truthy, the method binds listeners for"," * flick support. If false, the method unbinds flick listeners."," * @private"," */"," _bindFlick: function (flick) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'flick' listeners"," bb.detach(FLICK + '|*');",""," if (flick) {"," bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);",""," // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick"," sv._bindDrag(sv.get(DRAG));"," }"," },",""," /**"," * Bind (or unbind) mousewheel listeners."," *"," * @method _bindMousewheel"," * @param mousewheel {Object|boolean} If truthy, the method binds listeners for"," * mousewheel support. If false, the method unbinds mousewheel listeners."," * @private"," */"," _bindMousewheel: function (mousewheel) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'mousewheel' listeners"," // TODO: This doesn't actually appear to work properly. Fix. #2532743"," bb.detach(MOUSEWHEEL + '|*');",""," // Only enable for vertical scrollviews"," if (mousewheel) {"," // Bound to document, because that's where mousewheel events fire off of."," Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));"," }"," },",""," /**"," * syncUI implementation."," *"," * Update the scroll position, based on the current value of scrollX/scrollY."," *"," * @method syncUI"," */"," syncUI: function () {"," var sv = this,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight;",""," // If the axis is undefined, auto-calculate it"," if (sv._cAxis === undefined) {"," // This should only ever be run once (for now)."," // In the future SV might post-load axis changes"," sv._cAxis = {"," x: (scrollWidth > width),"," y: (scrollHeight > height)"," };",""," sv._set(AXIS, sv._cAxis);"," }",""," // get text direction on or inherited by scrollview node"," sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');",""," // Cache the disabled value"," sv._cDisabled = sv.get(DISABLED);",""," // Run this to set initial values"," sv._uiDimensionsChange();",""," // If we're out-of-bounds, snap back."," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," },",""," /**"," * Utility method to obtain widget dimensions"," *"," * @method _getScrollDims"," * @return {Object} The offsetWidth, offsetHeight, scrollWidth and"," * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,"," * scrollHeight]"," * @private"," */"," _getScrollDims: function () {"," var sv = this,"," cb = sv._cb,"," bb = sv._bb,"," TRANS = ScrollView._TRANSITION,"," // Ideally using CSSMatrix - don't think we have it normalized yet though."," // origX = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).e,"," // origY = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).f,"," origX = sv.get(SCROLL_X),"," origY = sv.get(SCROLL_Y),"," origHWTransform,"," dims;",""," // TODO: Is this OK? Just in case it's called 'during' a transition."," if (NATIVE_TRANSITIONS) {"," cb.setStyle(TRANS.DURATION, ZERO);"," cb.setStyle(TRANS.PROPERTY, EMPTY);"," }",""," origHWTransform = sv._forceHWTransforms;"," sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.",""," sv._moveTo(cb, 0, 0);"," dims = {"," 'offsetWidth': bb.get('offsetWidth'),"," 'offsetHeight': bb.get('offsetHeight'),"," 'scrollWidth': bb.get('scrollWidth'),"," 'scrollHeight': bb.get('scrollHeight')"," };"," sv._moveTo(cb, -(origX), -(origY));",""," sv._forceHWTransforms = origHWTransform;",""," return dims;"," },",""," /**"," * This method gets invoked whenever the height or width attributes change,"," * allowing us to determine which scrolling axes need to be enabled."," *"," * @method _uiDimensionsChange"," * @protected"," */"," _uiDimensionsChange: function () {"," var sv = this,"," bb = sv._bb,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight,"," rtl = sv.rtl,"," svAxis = sv._cAxis,"," minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),"," maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),"," minScrollY = 0,"," maxScrollY = Math.max(0, scrollHeight - height);",""," if (svAxis && svAxis.x) {"," bb.addClass(CLASS_NAMES.horizontal);"," }",""," if (svAxis && svAxis.y) {"," bb.addClass(CLASS_NAMES.vertical);"," }",""," sv._setBounds({"," minScrollX: minScrollX,"," maxScrollX: maxScrollX,"," minScrollY: minScrollY,"," maxScrollY: maxScrollY"," });"," },",""," /**"," * Set the bounding dimensions of the ScrollView"," *"," * @method _setBounds"," * @protected"," * @param bounds {Object} [duration] ms of the scroll animation. (default is 0)"," * @param {Number} [bounds.minScrollX] The minimum scroll X value"," * @param {Number} [bounds.maxScrollX] The maximum scroll X value"," * @param {Number} [bounds.minScrollY] The minimum scroll Y value"," * @param {Number} [bounds.maxScrollY] The maximum scroll Y value"," */"," _setBounds: function (bounds) {"," var sv = this;",""," // TODO: Do a check to log if the bounds are invalid",""," sv._minScrollX = bounds.minScrollX;"," sv._maxScrollX = bounds.maxScrollX;"," sv._minScrollY = bounds.minScrollY;"," sv._maxScrollY = bounds.maxScrollY;"," },",""," /**"," * Get the bounding dimensions of the ScrollView"," *"," * @method _getBounds"," * @protected"," */"," _getBounds: function () {"," var sv = this;",""," return {"," minScrollX: sv._minScrollX,"," maxScrollX: sv._maxScrollX,"," minScrollY: sv._minScrollY,"," maxScrollY: sv._maxScrollY"," };",""," },",""," /**"," * Scroll the element to a given xy coordinate"," *"," * @method scrollTo"," * @param x {Number} The x-position to scroll to. (null for no movement)"," * @param y {Number} The y-position to scroll to. (null for no movement)"," * @param {Number} [duration] ms of the scroll animation. (default is 0)"," * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)"," * @param {String} [node] The node to transform. Setting this can be useful in"," * dual-axis paginated instances. (default is the instance's contentBox)"," */"," scrollTo: function (x, y, duration, easing, node) {"," // Check to see if widget is disabled"," if (this._cDisabled) {"," return;"," }",""," var sv = this,"," cb = sv._cb,"," TRANS = ScrollView._TRANSITION,"," callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this"," newX = 0,"," newY = 0,"," transition = {},"," transform;",""," // default the optional arguments"," duration = duration || 0;"," easing = easing || sv.get(EASING); // @TODO: Cache this"," node = node || cb;",""," if (x !== null) {"," sv.set(SCROLL_X, x, {src:UI});"," newX = -(x);"," }",""," if (y !== null) {"," sv.set(SCROLL_Y, y, {src:UI});"," newY = -(y);"," }",""," transform = sv._transform(newX, newY);",""," if (NATIVE_TRANSITIONS) {"," // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one."," node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);"," }",""," // Move"," if (duration === 0) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', transform);"," }"," else {"," // TODO: If both set, batch them in the same update"," // Update: Nope, setStyles() just loops through each property and applies it."," if (x !== null) {"," node.setStyle(LEFT, newX + PX);"," }"," if (y !== null) {"," node.setStyle(TOP, newY + PX);"," }"," }"," }",""," // Animate"," else {"," transition.easing = easing;"," transition.duration = duration / 1000;",""," if (NATIVE_TRANSITIONS) {"," transition.transform = transform;"," }"," else {"," transition.left = newX + PX;"," transition.top = newY + PX;"," }",""," node.transition(transition, callback);"," }"," },",""," /**"," * Utility method, to create the translate transform string with the"," * x, y translation amounts provided."," *"," * @method _transform"," * @param {Number} x Number of pixels to translate along the x axis"," * @param {Number} y Number of pixels to translate along the y axis"," * @private"," */"," _transform: function (x, y) {"," // TODO: Would we be better off using a Matrix for this?"," var prop = 'translate(' + x + 'px, ' + y + 'px)';",""," if (this._forceHWTransforms) {"," prop += ' translateZ(0)';"," }",""," return prop;"," },",""," /**"," * Utility method, to move the given element to the given xy position"," *"," * @method _moveTo"," * @param node {Node} The node to move"," * @param x {Number} The x-position to move to"," * @param y {Number} The y-position to move to"," * @private"," */"," _moveTo : function(node, x, y) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', this._transform(x, y));"," } else {"," node.setStyle(LEFT, x + PX);"," node.setStyle(TOP, y + PX);"," }"," },","",""," /**"," * Content box transition callback"," *"," * @method _onTransEnd"," * @param {Event.Facade} e The event facade"," * @private"," */"," _onTransEnd: function () {"," var sv = this;",""," // If for some reason we're OOB, snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," else {"," /**"," * Notification event fired at the end of a scroll transition"," *"," * @event scrollEnd"," * @param e {EventFacade} The default event facade."," */"," sv.fire(EV_SCROLL_END);"," }"," },",""," /**"," * gesturemovestart event handler"," *"," * @method _onGestureMoveStart"," * @param e {Event.Facade} The gesturemovestart event facade"," * @private"," */"," _onGestureMoveStart: function (e) {",""," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," bb = sv._bb,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.start) {"," e.preventDefault();"," }",""," // if a flick animation is in progress, cancel it"," if (sv._flickAnim) {"," sv._cancelFlick();"," sv._onTransEnd();"," }",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Stores data for this gesture cycle. Cleaned up later"," sv._gesture = {",""," // Will hold the axis value"," axis: null,",""," // The current attribute values"," startX: currentX,"," startY: currentY,",""," // The X/Y coordinates where the event began"," startClientX: clientX,"," startClientY: clientY,",""," // The X/Y coordinates where the event will end"," endClientX: null,"," endClientY: null,",""," // The current delta of the event"," deltaX: null,"," deltaY: null,",""," // Will be populated for flicks"," flick: null,",""," // Create some listeners for the rest of the gesture cycle"," onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),",""," // @TODO: Don't bind gestureMoveEnd if it's a Flick?"," onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))"," };"," },",""," /**"," * gesturemove event handler"," *"," * @method _onGestureMove"," * @param e {Event.Facade} The gesturemove event facade"," * @private"," */"," _onGestureMove: function (e) {"," var sv = this,"," gesture = sv._gesture,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," startX = gesture.startX,"," startY = gesture.startY,"," startClientX = gesture.startClientX,"," startClientY = gesture.startClientY,"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.move) {"," e.preventDefault();"," }",""," gesture.deltaX = startClientX - clientX;"," gesture.deltaY = startClientY - clientY;",""," // Determine if this is a vertical or horizontal movement"," // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent"," if (gesture.axis === null) {"," gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;"," }",""," // Move X or Y. @TODO: Move both if dualaxis."," if (gesture.axis === DIM_X && svAxisX) {"," sv.set(SCROLL_X, startX + gesture.deltaX);"," }"," else if (gesture.axis === DIM_Y && svAxisY) {"," sv.set(SCROLL_Y, startY + gesture.deltaY);"," }"," },",""," /**"," * gesturemoveend event handler"," *"," * @method _onGestureMoveEnd"," * @param e {Event.Facade} The gesturemoveend event facade"," * @private"," */"," _onGestureMoveEnd: function (e) {"," var sv = this,"," gesture = sv._gesture,"," flick = gesture.flick,"," clientX = e.clientX,"," clientY = e.clientY,"," isOOB;",""," if (sv._prevent.end) {"," e.preventDefault();"," }",""," // Store the end X/Y coordinates"," gesture.endClientX = clientX;"," gesture.endClientY = clientY;",""," // Cleanup the event handlers"," gesture.onGestureMove.detach();"," gesture.onGestureMoveEnd.detach();",""," // If this wasn't a flick, wrap up the gesture cycle"," if (!flick) {"," // @TODO: Be more intelligent about this. Look at the Flick attribute to see"," // if it is safe to assume _flick did or didn't fire."," // Then, the order _flick and _onGestureMoveEnd fire doesn't matter?",""," // If there was movement (_onGestureMove fired)"," if (gesture.deltaX !== null && gesture.deltaY !== null) {",""," isOOB = sv._isOutOfBounds();",""," // If we're out-out-bounds, then snapback"," if (isOOB) {"," sv._snapBack();"," }",""," // Inbounds"," else {"," // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's"," // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit"," if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {"," sv._onTransEnd();"," }"," }"," }"," }"," },",""," /**"," * Execute a flick at the end of a scroll action"," *"," * @method _flick"," * @param e {Event.Facade} The Flick event facade"," * @private"," */"," _flick: function (e) {"," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," svAxis = sv._cAxis,"," flick = e.flick,"," flickAxis = flick.axis,"," flickVelocity = flick.velocity,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," startPosition = sv.get(axisAttr);",""," // Sometimes flick is enabled, but drag is disabled"," if (sv._gesture) {"," sv._gesture.flick = flick;"," }",""," // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis"," if (svAxis[flickAxis]) {"," sv._flickFrame(flickVelocity, flickAxis, startPosition);"," }"," },",""," /**"," * Execute a single frame in the flick animation"," *"," * @method _flickFrame"," * @param velocity {Number} The velocity of this animated frame"," * @param flickAxis {String} The axis on which to animate"," * @param startPosition {Number} The starting X/Y point to flick from"," * @protected"," */"," _flickFrame: function (velocity, flickAxis, startPosition) {",""," var sv = this,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," bounds = sv._getBounds(),",""," // Localize cached values"," bounce = sv._cBounce,"," bounceRange = sv._cBounceRange,"," deceleration = sv._cDeceleration,"," frameDuration = sv._cFrameDuration,",""," // Calculate"," newVelocity = velocity * deceleration,"," newPosition = startPosition - (frameDuration * newVelocity),",""," // Some convinience conditions"," min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,"," max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,"," belowMin = (newPosition < min),"," belowMax = (newPosition < max),"," aboveMin = (newPosition > min),"," aboveMax = (newPosition > max),"," belowMinRange = (newPosition < (min - bounceRange)),"," withinMinRange = (belowMin && (newPosition > (min - bounceRange))),"," withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),"," aboveMaxRange = (newPosition > (max + bounceRange)),"," tooSlow;",""," // If we're within the range but outside min/max, dampen the velocity"," if (withinMinRange || withinMaxRange) {"," newVelocity *= bounce;"," }",""," // Is the velocity too slow to bother?"," tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);",""," // If the velocity is too slow or we're outside the range"," if (tooSlow || belowMinRange || aboveMaxRange) {"," // Cancel and delete sv._flickAnim"," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // If we're inside the scroll area, just end"," if (aboveMin && belowMax) {"," sv._onTransEnd();"," }",""," // We're outside the scroll area, so we need to snap back"," else {"," sv._snapBack();"," }"," }",""," // Otherwise, animate to the next frame"," else {"," // @TODO: maybe use requestAnimationFrame instead"," sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);"," sv.set(axisAttr, newPosition);"," }"," },",""," _cancelFlick: function () {"," var sv = this;",""," if (sv._flickAnim) {"," // Cancel the flick (if it exists)"," sv._flickAnim.cancel();",""," // Also delete it, otherwise _onGestureMoveStart will think we're still flicking"," delete sv._flickAnim;"," }",""," },",""," /**"," * Handle mousewheel events on the widget"," *"," * @method _mousewheel"," * @param e {Event.Facade} The mousewheel event facade"," * @private"," */"," _mousewheel: function (e) {"," var sv = this,"," scrollY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," bb = sv._bb,"," scrollOffset = 10, // 10px"," isForward = (e.wheelDelta > 0),"," scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);",""," scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);",""," // Because Mousewheel events fire off 'document', every ScrollView widget will react"," // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently"," // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,"," // becuase otherwise the 'prevent' will block page scrolling."," if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Jump to the new offset"," sv.set(SCROLL_Y, scrollToY);",""," // if we have scrollbars plugin, update & set the flash timer on the scrollbar"," // @TODO: This probably shouldn't be in this module"," if (sv.scrollbars) {"," // @TODO: The scrollbars should handle this themselves"," sv.scrollbars._update();"," sv.scrollbars.flash();"," // or just this"," // sv.scrollbars._hostDimensionsChange();"," }",""," // Fire the 'scrollEnd' event"," sv._onTransEnd();",""," // prevent browser default behavior on mouse scroll"," e.preventDefault();"," }"," },",""," /**"," * Checks to see the current scrollX/scrollY position beyond the min/max boundary"," *"," * @method _isOutOfBounds"," * @param x {Number} [optional] The X position to check"," * @param y {Number} [optional] The Y position to check"," * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false)"," * @private"," */"," _isOutOfBounds: function (x, y) {"," var sv = this,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," currentX = x || sv.get(SCROLL_X),"," currentY = y || sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY;",""," return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));"," },",""," /**"," * Bounces back"," * @TODO: Should be more generalized and support both X and Y detection"," *"," * @method _snapBack"," * @private"," */"," _snapBack: function () {"," var sv = this,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY,"," newY = _constrain(currentY, minY, maxY),"," newX = _constrain(currentX, minX, maxX),"," duration = sv.get(SNAP_DURATION),"," easing = sv.get(SNAP_EASING);",""," if (newX !== currentX) {"," sv.set(SCROLL_X, newX, {duration:duration, easing:easing});"," }"," else if (newY !== currentY) {"," sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});"," }"," else {"," sv._onTransEnd();"," }"," },",""," /**"," * After listener for changes to the scrollX or scrollY attribute"," *"," * @method _afterScrollChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollChange: function (e) {"," if (e.src === ScrollView.UI_SRC) {"," return false;"," }",""," var sv = this,"," duration = e.duration,"," easing = e.easing,"," val = e.newVal,"," scrollToArgs = [];",""," // Set the scrolled value"," sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);",""," // Generate the array of args to pass to scrollTo()"," if (e.attrName === SCROLL_X) {"," scrollToArgs.push(val);"," scrollToArgs.push(sv.get(SCROLL_Y));"," }"," else {"," scrollToArgs.push(sv.get(SCROLL_X));"," scrollToArgs.push(val);"," }",""," scrollToArgs.push(duration);"," scrollToArgs.push(easing);",""," sv.scrollTo.apply(sv, scrollToArgs);"," },",""," /**"," * After listener for changes to the flick attribute"," *"," * @method _afterFlickChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterFlickChange: function (e) {"," this._bindFlick(e.newVal);"," },",""," /**"," * After listener for changes to the disabled attribute"," *"," * @method _afterDisabledChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDisabledChange: function (e) {"," // Cache for performance - we check during move"," this._cDisabled = e.newVal;"," },",""," /**"," * After listener for the axis attribute"," *"," * @method _afterAxisChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterAxisChange: function (e) {"," this._cAxis = e.newVal;"," },",""," /**"," * After listener for changes to the drag attribute"," *"," * @method _afterDragChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDragChange: function (e) {"," this._bindDrag(e.newVal);"," },",""," /**"," * After listener for the height or width attribute"," *"," * @method _afterDimChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDimChange: function () {"," this._uiDimensionsChange();"," },",""," /**"," * After listener for scrollEnd, for cleanup"," *"," * @method _afterScrollEnd"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollEnd: function () {"," var sv = this;",""," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // Ideally this should be removed, but doing so causing some JS errors with fast swiping"," // because _gesture is being deleted after the previous one has been overwritten"," // delete sv._gesture; // TODO: Move to sv.prevGesture?"," },",""," /**"," * Setter for 'axis' attribute"," *"," * @method _axisSetter"," * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on"," * @param name {String} The attribute name"," * @return {Object} An object to specify scrollability on the x & y axes"," *"," * @protected"," */"," _axisSetter: function (val) {",""," // Turn a string into an axis object"," if (Y.Lang.isString(val)) {"," return {"," x: val.match(/x/i) ? true : false,"," y: val.match(/y/i) ? true : false"," };"," }"," },",""," /**"," * The scrollX, scrollY setter implementation"," *"," * @method _setScroll"," * @private"," * @param {Number} val"," * @param {String} dim"," *"," * @return {Number} The value"," */"," _setScroll : function(val) {",""," // Just ensure the widget is not disabled"," if (this._cDisabled) {"," val = Y.Attribute.INVALID_VALUE;"," }",""," return val;"," },",""," /**"," * Setter for the scrollX attribute"," *"," * @method _setScrollX"," * @param val {Number} The new scrollX value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollX: function(val) {"," return this._setScroll(val, DIM_X);"," },",""," /**"," * Setter for the scrollY ATTR"," *"," * @method _setScrollY"," * @param val {Number} The new scrollY value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollY: function(val) {"," return this._setScroll(val, DIM_Y);"," }",""," // End prototype properties","","}, {",""," // Static properties",""," /**"," * The identity of the widget."," *"," * @property NAME"," * @type String"," * @default 'scrollview'"," * @readOnly"," * @protected"," * @static"," */"," NAME: 'scrollview',",""," /**"," * Static property used to define the default attribute configuration of"," * the Widget."," *"," * @property ATTRS"," * @type {Object}"," * @protected"," * @static"," */"," ATTRS: {",""," /**"," * Specifies ability to scroll on x, y, or x and y axis/axes."," *"," * @attribute axis"," * @type String"," */"," axis: {"," setter: '_axisSetter',"," writeOnce: 'initOnly'"," },",""," /**"," * The current scroll position in the x-axis"," *"," * @attribute scrollX"," * @type Number"," * @default 0"," */"," scrollX: {"," value: 0,"," setter: '_setScrollX'"," },",""," /**"," * The current scroll position in the y-axis"," *"," * @attribute scrollY"," * @type Number"," * @default 0"," */"," scrollY: {"," value: 0,"," setter: '_setScrollY'"," },",""," /**"," * Drag coefficent for inertial scrolling. The closer to 1 this"," * value is, the less friction during scrolling."," *"," * @attribute deceleration"," * @default 0.93"," */"," deceleration: {"," value: 0.93"," },",""," /**"," * Drag coefficient for intertial scrolling at the upper"," * and lower boundaries of the scrollview. Set to 0 to"," * disable \"rubber-banding\"."," *"," * @attribute bounce"," * @type Number"," * @default 0.1"," */"," bounce: {"," value: 0.1"," },",""," /**"," * The minimum distance and/or velocity which define a flick. Can be set to false,"," * to disable flick support (note: drag support is enabled/disabled separately)"," *"," * @attribute flick"," * @type Object"," * @default Object with properties minDistance = 10, minVelocity = 0.3."," */"," flick: {"," value: {"," minDistance: 10,"," minVelocity: 0.3"," }"," },",""," /**"," * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)"," * @attribute drag"," * @type boolean"," * @default true"," */"," drag: {"," value: true"," },",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @attribute snapDuration"," * @type Number"," * @default 400"," */"," snapDuration: {"," value: 400"," },",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @attribute snapEasing"," * @type String"," * @default 'ease-out'"," */"," snapEasing: {"," value: 'ease-out'"," },",""," /**"," * The default easing used when animating the flick"," *"," * @attribute easing"," * @type String"," * @default 'cubic-bezier(0, 0.1, 0, 1.0)'"," */"," easing: {"," value: 'cubic-bezier(0, 0.1, 0, 1.0)'"," },",""," /**"," * The interval (ms) used when animating the flick for JS-timer animations"," *"," * @attribute frameDuration"," * @type Number"," * @default 15"," */"," frameDuration: {"," value: 15"," },",""," /**"," * The default bounce distance in pixels"," *"," * @attribute bounceRange"," * @type Number"," * @default 150"," */"," bounceRange: {"," value: 150"," }"," },",""," /**"," * List of class names used in the scrollview's DOM"," *"," * @property CLASS_NAMES"," * @type Object"," * @static"," */"," CLASS_NAMES: CLASS_NAMES,",""," /**"," * Flag used to source property changes initiated from the DOM"," *"," * @property UI_SRC"," * @type String"," * @static"," * @default 'ui'"," */"," UI_SRC: UI,",""," /**"," * Object map of style property names used to set transition properties."," * Defaults to the vendor prefix established by the Transition module."," * The configured property names are `_TRANSITION.DURATION` (e.g. \"WebkitTransitionDuration\") and"," * `_TRANSITION.PROPERTY (e.g. \"WebkitTransitionProperty\")."," *"," * @property _TRANSITION"," * @private"," */"," _TRANSITION: {"," DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),"," PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')"," },",""," /**"," * The default bounce distance in pixels"," *"," * @property BOUNCE_RANGE"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," BOUNCE_RANGE: false,",""," /**"," * The interval (ms) used when animating the flick"," *"," * @property FRAME_STEP"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," FRAME_STEP: false,",""," /**"," * The default easing used when animating the flick"," *"," * @property EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," EASING: false,",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @property SNAP_EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_EASING: false,",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @property SNAP_DURATION"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_DURATION: false",""," // End static properties","","});","","","}, '3.14.1', {\"requires\": [\"widget\", \"event-gestures\", \"event-mousewheel\", \"transition\"], \"skinnable\": true});","","}());"]};
}
var __cov_cyIK2vRXoVgOuWid4NBKqw = __coverage__['build/scrollview-base/scrollview-base.js'];
__cov_cyIK2vRXoVgOuWid4NBKqw.s['1']++;YUI.add('scrollview-base',function(Y,NAME){__cov_cyIK2vRXoVgOuWid4NBKqw.f['1']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['2']++;var getClassName=Y.ClassNameManager.getClassName,DOCUMENT=Y.config.doc,IE=Y.UA.ie,NATIVE_TRANSITIONS=Y.Transition.useNative,vendorPrefix=Y.Transition._VENDOR_PREFIX,SCROLLVIEW='scrollview',CLASS_NAMES={vertical:getClassName(SCROLLVIEW,'vert'),horizontal:getClassName(SCROLLVIEW,'horiz')},EV_SCROLL_END='scrollEnd',FLICK='flick',DRAG='drag',MOUSEWHEEL='mousewheel',UI='ui',TOP='top',LEFT='left',PX='px',AXIS='axis',SCROLL_Y='scrollY',SCROLL_X='scrollX',BOUNCE='bounce',DISABLED='disabled',DECELERATION='deceleration',DIM_X='x',DIM_Y='y',BOUNDING_BOX='boundingBox',CONTENT_BOX='contentBox',GESTURE_MOVE='gesturemove',START='start',END='end',EMPTY='',ZERO='0s',SNAP_DURATION='snapDuration',SNAP_EASING='snapEasing',EASING='easing',FRAME_DURATION='frameDuration',BOUNCE_RANGE='bounceRange',_constrain=function(val,min,max){__cov_cyIK2vRXoVgOuWid4NBKqw.f['2']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['3']++;return Math.min(Math.max(val,min),max);};__cov_cyIK2vRXoVgOuWid4NBKqw.s['4']++;function ScrollView(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['3']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['5']++;ScrollView.superclass.constructor.apply(this,arguments);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['6']++;Y.ScrollView=Y.extend(ScrollView,Y.Widget,{_forceHWTransforms:Y.UA.webkit?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][1]++,false),_prevent:{start:false,move:true,end:false},lastScrolledAmt:0,_minScrollX:null,_maxScrollX:null,_minScrollY:null,_maxScrollY:null,initializer:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['4']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['7']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['8']++;sv._bb=sv.get(BOUNDING_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['9']++;sv._cb=sv.get(CONTENT_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['10']++;sv._cAxis=sv.get(AXIS);__cov_cyIK2vRXoVgOuWid4NBKqw.s['11']++;sv._cBounce=sv.get(BOUNCE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['12']++;sv._cBounceRange=sv.get(BOUNCE_RANGE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['13']++;sv._cDeceleration=sv.get(DECELERATION);__cov_cyIK2vRXoVgOuWid4NBKqw.s['14']++;sv._cFrameDuration=sv.get(FRAME_DURATION);},bindUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['5']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['15']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['16']++;sv._bindFlick(sv.get(FLICK));__cov_cyIK2vRXoVgOuWid4NBKqw.s['17']++;sv._bindDrag(sv.get(DRAG));__cov_cyIK2vRXoVgOuWid4NBKqw.s['18']++;sv._bindMousewheel(true);__cov_cyIK2vRXoVgOuWid4NBKqw.s['19']++;sv._bindAttrs();__cov_cyIK2vRXoVgOuWid4NBKqw.s['20']++;if(IE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['21']++;sv._fixIESelect(sv._bb,sv._cb);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['22']++;if(ScrollView.SNAP_DURATION){__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['23']++;sv.set(SNAP_DURATION,ScrollView.SNAP_DURATION);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['24']++;if(ScrollView.SNAP_EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['25']++;sv.set(SNAP_EASING,ScrollView.SNAP_EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['26']++;if(ScrollView.EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['27']++;sv.set(EASING,ScrollView.EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['28']++;if(ScrollView.FRAME_STEP){__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['29']++;sv.set(FRAME_DURATION,ScrollView.FRAME_STEP);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['30']++;if(ScrollView.BOUNCE_RANGE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['31']++;sv.set(BOUNCE_RANGE,ScrollView.BOUNCE_RANGE);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][1]++;}},_bindAttrs:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['6']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['32']++;var sv=this,scrollChangeHandler=sv._afterScrollChange,dimChangeHandler=sv._afterDimChange;__cov_cyIK2vRXoVgOuWid4NBKqw.s['33']++;sv.after({'scrollEnd':sv._afterScrollEnd,'disabledChange':sv._afterDisabledChange,'flickChange':sv._afterFlickChange,'dragChange':sv._afterDragChange,'axisChange':sv._afterAxisChange,'scrollYChange':scrollChangeHandler,'scrollXChange':scrollChangeHandler,'heightChange':dimChangeHandler,'widthChange':dimChangeHandler});},_bindDrag:function(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.f['7']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['34']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['35']++;bb.detach(DRAG+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['36']++;if(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['37']++;bb.on(DRAG+'|'+GESTURE_MOVE+START,Y.bind(sv._onGestureMoveStart,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][1]++;}},_bindFlick:function(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.f['8']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['38']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['39']++;bb.detach(FLICK+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['40']++;if(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['41']++;bb.on(FLICK+'|'+FLICK,Y.bind(sv._flick,sv),flick);__cov_cyIK2vRXoVgOuWid4NBKqw.s['42']++;sv._bindDrag(sv.get(DRAG));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][1]++;}},_bindMousewheel:function(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.f['9']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['43']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['44']++;bb.detach(MOUSEWHEEL+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['45']++;if(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['46']++;Y.one(DOCUMENT).on(MOUSEWHEEL,Y.bind(sv._mousewheel,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][1]++;}},syncUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['10']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['47']++;var sv=this,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight;__cov_cyIK2vRXoVgOuWid4NBKqw.s['48']++;if(sv._cAxis===undefined){__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['49']++;sv._cAxis={x:scrollWidth>width,y:scrollHeight>height};__cov_cyIK2vRXoVgOuWid4NBKqw.s['50']++;sv._set(AXIS,sv._cAxis);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['51']++;sv.rtl=sv._cb.getComputedStyle('direction')==='rtl';__cov_cyIK2vRXoVgOuWid4NBKqw.s['52']++;sv._cDisabled=sv.get(DISABLED);__cov_cyIK2vRXoVgOuWid4NBKqw.s['53']++;sv._uiDimensionsChange();__cov_cyIK2vRXoVgOuWid4NBKqw.s['54']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['55']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][1]++;}},_getScrollDims:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['11']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['56']++;var sv=this,cb=sv._cb,bb=sv._bb,TRANS=ScrollView._TRANSITION,origX=sv.get(SCROLL_X),origY=sv.get(SCROLL_Y),origHWTransform,dims;__cov_cyIK2vRXoVgOuWid4NBKqw.s['57']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['58']++;cb.setStyle(TRANS.DURATION,ZERO);__cov_cyIK2vRXoVgOuWid4NBKqw.s['59']++;cb.setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['60']++;origHWTransform=sv._forceHWTransforms;__cov_cyIK2vRXoVgOuWid4NBKqw.s['61']++;sv._forceHWTransforms=false;__cov_cyIK2vRXoVgOuWid4NBKqw.s['62']++;sv._moveTo(cb,0,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['63']++;dims={'offsetWidth':bb.get('offsetWidth'),'offsetHeight':bb.get('offsetHeight'),'scrollWidth':bb.get('scrollWidth'),'scrollHeight':bb.get('scrollHeight')};__cov_cyIK2vRXoVgOuWid4NBKqw.s['64']++;sv._moveTo(cb,-origX,-origY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['65']++;sv._forceHWTransforms=origHWTransform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['66']++;return dims;},_uiDimensionsChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['12']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['67']++;var sv=this,bb=sv._bb,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight,rtl=sv.rtl,svAxis=sv._cAxis,minScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][0]++,Math.min(0,-(scrollWidth-width))):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][1]++,0),maxScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][0]++,0):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][1]++,Math.max(0,scrollWidth-width)),minScrollY=0,maxScrollY=Math.max(0,scrollHeight-height);__cov_cyIK2vRXoVgOuWid4NBKqw.s['68']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][1]++,svAxis.x)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['69']++;bb.addClass(CLASS_NAMES.horizontal);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['70']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][1]++,svAxis.y)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['71']++;bb.addClass(CLASS_NAMES.vertical);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['72']++;sv._setBounds({minScrollX:minScrollX,maxScrollX:maxScrollX,minScrollY:minScrollY,maxScrollY:maxScrollY});},_setBounds:function(bounds){__cov_cyIK2vRXoVgOuWid4NBKqw.f['13']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['73']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['74']++;sv._minScrollX=bounds.minScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['75']++;sv._maxScrollX=bounds.maxScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['76']++;sv._minScrollY=bounds.minScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['77']++;sv._maxScrollY=bounds.maxScrollY;},_getBounds:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['14']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['78']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['79']++;return{minScrollX:sv._minScrollX,maxScrollX:sv._maxScrollX,minScrollY:sv._minScrollY,maxScrollY:sv._maxScrollY};},scrollTo:function(x,y,duration,easing,node){__cov_cyIK2vRXoVgOuWid4NBKqw.f['15']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['80']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['81']++;return;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['82']++;var sv=this,cb=sv._cb,TRANS=ScrollView._TRANSITION,callback=Y.bind(sv._onTransEnd,sv),newX=0,newY=0,transition={},transform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['83']++;duration=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][0]++,duration)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][1]++,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['84']++;easing=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][0]++,easing)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][1]++,sv.get(EASING));__cov_cyIK2vRXoVgOuWid4NBKqw.s['85']++;node=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][0]++,node)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][1]++,cb);__cov_cyIK2vRXoVgOuWid4NBKqw.s['86']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['87']++;sv.set(SCROLL_X,x,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['88']++;newX=-x;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['89']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['90']++;sv.set(SCROLL_Y,y,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['91']++;newY=-y;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['92']++;transform=sv._transform(newX,newY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['93']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['94']++;node.setStyle(TRANS.DURATION,ZERO).setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['95']++;if(duration===0){__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['96']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['97']++;node.setStyle('transform',transform);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['98']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['99']++;node.setStyle(LEFT,newX+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['100']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['101']++;node.setStyle(TOP,newY+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['102']++;transition.easing=easing;__cov_cyIK2vRXoVgOuWid4NBKqw.s['103']++;transition.duration=duration/1000;__cov_cyIK2vRXoVgOuWid4NBKqw.s['104']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['105']++;transition.transform=transform;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['106']++;transition.left=newX+PX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['107']++;transition.top=newY+PX;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['108']++;node.transition(transition,callback);}},_transform:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['16']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['109']++;var prop='translate('+x+'px, '+y+'px)';__cov_cyIK2vRXoVgOuWid4NBKqw.s['110']++;if(this._forceHWTransforms){__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['111']++;prop+=' translateZ(0)';}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['112']++;return prop;},_moveTo:function(node,x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['17']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['113']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['114']++;node.setStyle('transform',this._transform(x,y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['115']++;node.setStyle(LEFT,x+PX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['116']++;node.setStyle(TOP,y+PX);}},_onTransEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['18']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['117']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['118']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['119']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['120']++;sv.fire(EV_SCROLL_END);}},_onGestureMoveStart:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['19']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['121']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['122']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['123']++;var sv=this,bb=sv._bb,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['124']++;if(sv._prevent.start){__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['125']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['126']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['127']++;sv._cancelFlick();__cov_cyIK2vRXoVgOuWid4NBKqw.s['128']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['129']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['130']++;sv._gesture={axis:null,startX:currentX,startY:currentY,startClientX:clientX,startClientY:clientY,endClientX:null,endClientY:null,deltaX:null,deltaY:null,flick:null,onGestureMove:bb.on(DRAG+'|'+GESTURE_MOVE,Y.bind(sv._onGestureMove,sv)),onGestureMoveEnd:bb.on(DRAG+'|'+GESTURE_MOVE+END,Y.bind(sv._onGestureMoveEnd,sv))};},_onGestureMove:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['20']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['131']++;var sv=this,gesture=sv._gesture,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,startX=gesture.startX,startY=gesture.startY,startClientX=gesture.startClientX,startClientY=gesture.startClientY,clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['132']++;if(sv._prevent.move){__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['133']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['134']++;gesture.deltaX=startClientX-clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['135']++;gesture.deltaY=startClientY-clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['136']++;if(gesture.axis===null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['137']++;gesture.axis=Math.abs(gesture.deltaX)>Math.abs(gesture.deltaY)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][0]++,DIM_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][1]++,DIM_Y);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['138']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][0]++,gesture.axis===DIM_X)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][1]++,svAxisX)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['139']++;sv.set(SCROLL_X,startX+gesture.deltaX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['140']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][0]++,gesture.axis===DIM_Y)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][1]++,svAxisY)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['141']++;sv.set(SCROLL_Y,startY+gesture.deltaY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][1]++;}}},_onGestureMoveEnd:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['21']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['142']++;var sv=this,gesture=sv._gesture,flick=gesture.flick,clientX=e.clientX,clientY=e.clientY,isOOB;__cov_cyIK2vRXoVgOuWid4NBKqw.s['143']++;if(sv._prevent.end){__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['144']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['145']++;gesture.endClientX=clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['146']++;gesture.endClientY=clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['147']++;gesture.onGestureMove.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['148']++;gesture.onGestureMoveEnd.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['149']++;if(!flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['150']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][0]++,gesture.deltaX!==null)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][1]++,gesture.deltaY!==null)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['151']++;isOOB=sv._isOutOfBounds();__cov_cyIK2vRXoVgOuWid4NBKqw.s['152']++;if(isOOB){__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['153']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['154']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][0]++,!sv.pages)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][1]++,sv.pages)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][2]++,!sv.pages.get(AXIS)[gesture.axis])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['155']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][1]++;}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][1]++;}},_flick:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['22']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['156']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['157']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['158']++;var sv=this,svAxis=sv._cAxis,flick=e.flick,flickAxis=flick.axis,flickVelocity=flick.velocity,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][1]++,SCROLL_Y),startPosition=sv.get(axisAttr);__cov_cyIK2vRXoVgOuWid4NBKqw.s['159']++;if(sv._gesture){__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['160']++;sv._gesture.flick=flick;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['161']++;if(svAxis[flickAxis]){__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['162']++;sv._flickFrame(flickVelocity,flickAxis,startPosition);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][1]++;}},_flickFrame:function(velocity,flickAxis,startPosition){__cov_cyIK2vRXoVgOuWid4NBKqw.f['23']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['163']++;var sv=this,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][1]++,SCROLL_Y),bounds=sv._getBounds(),bounce=sv._cBounce,bounceRange=sv._cBounceRange,deceleration=sv._cDeceleration,frameDuration=sv._cFrameDuration,newVelocity=velocity*deceleration,newPosition=startPosition-frameDuration*newVelocity,min=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][0]++,bounds.minScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][1]++,bounds.minScrollY),max=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][0]++,bounds.maxScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][1]++,bounds.maxScrollY),belowMin=newPosition<min,belowMax=newPosition<max,aboveMin=newPosition>min,aboveMax=newPosition>max,belowMinRange=newPosition<min-bounceRange,withinMinRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][0]++,belowMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][1]++,newPosition>min-bounceRange),withinMaxRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][0]++,aboveMax)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][1]++,newPosition<max+bounceRange),aboveMaxRange=newPosition>max+bounceRange,tooSlow;__cov_cyIK2vRXoVgOuWid4NBKqw.s['164']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][0]++,withinMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][1]++,withinMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['165']++;newVelocity*=bounce;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['166']++;tooSlow=Math.abs(newVelocity).toFixed(4)<0.015;__cov_cyIK2vRXoVgOuWid4NBKqw.s['167']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][0]++,tooSlow)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][1]++,belowMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][2]++,aboveMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['168']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['169']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['170']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][0]++,aboveMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][1]++,belowMax)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['171']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['172']++;sv._snapBack();}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['173']++;sv._flickAnim=Y.later(frameDuration,sv,'_flickFrame',[newVelocity,flickAxis,newPosition]);__cov_cyIK2vRXoVgOuWid4NBKqw.s['174']++;sv.set(axisAttr,newPosition);}},_cancelFlick:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['24']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['175']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['176']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['177']++;sv._flickAnim.cancel();__cov_cyIK2vRXoVgOuWid4NBKqw.s['178']++;delete sv._flickAnim;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][1]++;}},_mousewheel:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['25']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['179']++;var sv=this,scrollY=sv.get(SCROLL_Y),bounds=sv._getBounds(),bb=sv._bb,scrollOffset=10,isForward=e.wheelDelta>0,scrollToY=scrollY-(isForward?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][0]++,1):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][1]++,-1))*scrollOffset;__cov_cyIK2vRXoVgOuWid4NBKqw.s['180']++;scrollToY=_constrain(scrollToY,bounds.minScrollY,bounds.maxScrollY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['181']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][0]++,bb.contains(e.target))&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][1]++,sv._cAxis[DIM_Y])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['182']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['183']++;sv.set(SCROLL_Y,scrollToY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['184']++;if(sv.scrollbars){__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['185']++;sv.scrollbars._update();__cov_cyIK2vRXoVgOuWid4NBKqw.s['186']++;sv.scrollbars.flash();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['187']++;sv._onTransEnd();__cov_cyIK2vRXoVgOuWid4NBKqw.s['188']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][1]++;}},_isOutOfBounds:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['26']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['189']++;var sv=this,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,currentX=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][0]++,x)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][1]++,sv.get(SCROLL_X)),currentY=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][0]++,y)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][1]++,sv.get(SCROLL_Y)),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['190']++;return(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][0]++,svAxisX)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][1]++,currentX<minX)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][2]++,currentX>maxX))||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][3]++,svAxisY)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][4]++,currentY<minY)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][5]++,currentY>maxY));},_snapBack:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['27']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['191']++;var sv=this,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY,newY=_constrain(currentY,minY,maxY),newX=_constrain(currentX,minX,maxX),duration=sv.get(SNAP_DURATION),easing=sv.get(SNAP_EASING);__cov_cyIK2vRXoVgOuWid4NBKqw.s['192']++;if(newX!==currentX){__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['193']++;sv.set(SCROLL_X,newX,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['194']++;if(newY!==currentY){__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['195']++;sv.set(SCROLL_Y,newY,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['196']++;sv._onTransEnd();}}},_afterScrollChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['28']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['197']++;if(e.src===ScrollView.UI_SRC){__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['198']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['199']++;var sv=this,duration=e.duration,easing=e.easing,val=e.newVal,scrollToArgs=[];__cov_cyIK2vRXoVgOuWid4NBKqw.s['200']++;sv.lastScrolledAmt=sv.lastScrolledAmt+(e.newVal-e.prevVal);__cov_cyIK2vRXoVgOuWid4NBKqw.s['201']++;if(e.attrName===SCROLL_X){__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['202']++;scrollToArgs.push(val);__cov_cyIK2vRXoVgOuWid4NBKqw.s['203']++;scrollToArgs.push(sv.get(SCROLL_Y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['204']++;scrollToArgs.push(sv.get(SCROLL_X));__cov_cyIK2vRXoVgOuWid4NBKqw.s['205']++;scrollToArgs.push(val);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['206']++;scrollToArgs.push(duration);__cov_cyIK2vRXoVgOuWid4NBKqw.s['207']++;scrollToArgs.push(easing);__cov_cyIK2vRXoVgOuWid4NBKqw.s['208']++;sv.scrollTo.apply(sv,scrollToArgs);},_afterFlickChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['29']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['209']++;this._bindFlick(e.newVal);},_afterDisabledChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['30']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['210']++;this._cDisabled=e.newVal;},_afterAxisChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['31']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['211']++;this._cAxis=e.newVal;},_afterDragChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['32']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['212']++;this._bindDrag(e.newVal);},_afterDimChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['33']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['213']++;this._uiDimensionsChange();},_afterScrollEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['34']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['214']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['215']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['216']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][1]++;}},_axisSetter:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['35']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['217']++;if(Y.Lang.isString(val)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['218']++;return{x:val.match(/x/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][1]++,false),y:val.match(/y/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][1]++,false)};}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][1]++;}},_setScroll:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['36']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['219']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['220']++;val=Y.Attribute.INVALID_VALUE;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['221']++;return val;},_setScrollX:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['37']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['222']++;return this._setScroll(val,DIM_X);},_setScrollY:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['38']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['223']++;return this._setScroll(val,DIM_Y);}},{NAME:'scrollview',ATTRS:{axis:{setter:'_axisSetter',writeOnce:'initOnly'},scrollX:{value:0,setter:'_setScrollX'},scrollY:{value:0,setter:'_setScrollY'},deceleration:{value:0.93},bounce:{value:0.1},flick:{value:{minDistance:10,minVelocity:0.3}},drag:{value:true},snapDuration:{value:400},snapEasing:{value:'ease-out'},easing:{value:'cubic-bezier(0, 0.1, 0, 1.0)'},frameDuration:{value:15},bounceRange:{value:150}},CLASS_NAMES:CLASS_NAMES,UI_SRC:UI,_TRANSITION:{DURATION:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][0]++,vendorPrefix+'TransitionDuration'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][1]++,'transitionDuration'),PROPERTY:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][0]++,vendorPrefix+'TransitionProperty'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][1]++,'transitionProperty')},BOUNCE_RANGE:false,FRAME_STEP:false,EASING:false,SNAP_EASING:false,SNAP_DURATION:false});},'3.14.1',{'requires':['widget','event-gestures','event-mousewheel','transition'],'skinnable':true});
|
client/src/HeaderPresenter.js | ahorrocks2/what_sounds_good_to_you | import React from 'react';
const HeaderPresenter = () => {
return (
<div className="header">
<h1 className="headerText">the hanger helper.</h1>
</div>
);
}
export default HeaderPresenter;
|
client/app/containers/Blending/index.js | vulcan-estudios/pwa-examples | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { startBlending, stopBlending } from 'client/app/actions';
import Blender from 'client/app/components/Blender';
const mapStateToProps = function (state) {
return {
app: state.app,
fruits: state.fruits,
recipes: state.recipes,
};
};
const mapDispatchToProps = function (dispatch) {
return {
handleStartBlending: (data) => dispatch(startBlending(data)),
handleStopBlending: (data) => dispatch(stopBlending(data)),
};
};
class BlendingContainer extends Component {
constructor () {
super(...arguments);
}
componentDidMount () {
const { router, route } = this.props;
const { handleStopBlending } = this.props;
router.setRouteLeaveHook(route, () => handleStopBlending());
}
componentWillUnmount () {
const { handleStopBlending } = this.props;
handleStopBlending();
}
render () {
const { params, app, fruits, recipes } = this.props;
const { handleStartBlending, handleStopBlending } = this.props;
const { recipeId } = params;
const { user: cookId } = app;
const isOn = !!app.current;
const progress = app.current && app.current.progress || 0;
const recipe = recipes.find(recip => recip.id === recipeId);
let recipeFruits = recipe.fruits.map(fruitId => fruits.find(f => f.id === fruitId));
if (!recipeFruits.length) {
recipeFruits = [ ...fruits ];
recipeFruits.length = recipeFruits.length > 4 ? 4 : recipeFruits.length;
}
while (recipeFruits.length > 0 && recipeFruits.length < 4) {
recipeFruits = recipeFruits.concat(recipeFruits);
}
const buttonEl = isOn ? (
<button
className='button alert'
onClick={handleStopBlending}
>
Stop
</button>
) : (
<button
className='button'
onClick={() => handleStartBlending({ recipeId, cookId })}
>
Start
</button>
);
return (
<div className='blending row column'>
<Blender isOn={isOn} recipe={recipe} fruits={recipeFruits} progress={progress} />
<div className='row column text-center'>
{buttonEl}
</div>
</div>
);
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(BlendingContainer));
|
files/knockout.validation/2.0.3/knockout.validation.js | as-com/jsdelivr | /*=============================================================================
Author: Eric M. Barnard - @ericmbarnard
License: MIT (http://opensource.org/licenses/mit-license.php)
Description: Validation Library for KnockoutJS
Version: 2.0.3
===============================================================================
*/
/*globals require: false, exports: false, define: false, ko: false */
(function (factory) {
// Module systems magic dance.
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS or Node: hard-coded dependency on "knockout"
factory(require("knockout"), exports);
} else if (typeof define === "function" && define["amd"]) {
// AMD anonymous module with hard-coded dependency on "knockout"
define(["knockout", "exports"], factory);
} else {
// <script> tag: use the global `ko` object, attaching a `mapping` property
factory(ko, ko.validation = {});
}
}(function ( ko, exports ) {
if (typeof (ko) === 'undefined') {
throw new Error('Knockout is required, please ensure it is loaded before loading this validation plug-in');
}
// create our namespace object
ko.validation = exports;
var kv = ko.validation,
koUtils = ko.utils,
unwrap = koUtils.unwrapObservable,
forEach = koUtils.arrayForEach,
extend = koUtils.extend;
;/*global ko: false*/
var defaults = {
registerExtenders: true,
messagesOnModified: true,
errorsAsTitle: true, // enables/disables showing of errors as title attribute of the target element.
errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true)
messageTemplate: null,
insertMessages: true, // automatically inserts validation messages as <span></span>
parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object
writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to
decorateInputElement: false, // false to keep backward compatibility
decorateElementOnModified: true,// true to keep backward compatibility
errorClass: null, // single class for error message and element
errorElementClass: 'validationElement', // class to decorate error element
errorMessageClass: 'validationMessage', // class to decorate error message
allowHtmlMessages: false, // allows HTML in validation messages
grouping: {
deep: false, //by default grouping is shallow
observable: true, //and using observables
live: false //react to changes to observableArrays if observable === true
},
validate: {
// throttle: 10
}
};
// make a copy so we can use 'reset' later
var configuration = extend({}, defaults);
configuration.html5Attributes = ['required', 'pattern', 'min', 'max', 'step'];
configuration.html5InputTypes = ['email', 'number', 'date'];
configuration.reset = function () {
extend(configuration, defaults);
};
kv.configuration = configuration;
;kv.utils = (function () {
var seedId = new Date().getTime();
var domData = {}; //hash of data objects that we reference from dom elements
var domDataKey = '__ko_validation__';
return {
isArray: function (o) {
return o.isArray || Object.prototype.toString.call(o) === '[object Array]';
},
isObject: function (o) {
return o !== null && typeof o === 'object';
},
isNumber: function(o) {
return !isNaN(o);
},
isObservableArray: function(instance) {
return !!instance &&
typeof instance["remove"] === "function" &&
typeof instance["removeAll"] === "function" &&
typeof instance["destroy"] === "function" &&
typeof instance["destroyAll"] === "function" &&
typeof instance["indexOf"] === "function" &&
typeof instance["replace"] === "function";
},
values: function (o) {
var r = [];
for (var i in o) {
if (o.hasOwnProperty(i)) {
r.push(o[i]);
}
}
return r;
},
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
hasAttribute: function (node, attr) {
return node.getAttribute(attr) !== null;
},
getAttribute: function (element, attr) {
return element.getAttribute(attr);
},
setAttribute: function (element, attr, value) {
return element.setAttribute(attr, value);
},
isValidatable: function (o) {
return !!(o && o.rules && o.isValid && o.isModified);
},
insertAfter: function (node, newNode) {
node.parentNode.insertBefore(newNode, node.nextSibling);
},
newId: function () {
return seedId += 1;
},
getConfigOptions: function (element) {
var options = kv.utils.contextFor(element);
return options || kv.configuration;
},
setDomData: function (node, data) {
var key = node[domDataKey];
if (!key) {
node[domDataKey] = key = kv.utils.newId();
}
domData[key] = data;
},
getDomData: function (node) {
var key = node[domDataKey];
if (!key) {
return undefined;
}
return domData[key];
},
contextFor: function (node) {
switch (node.nodeType) {
case 1:
case 8:
var context = kv.utils.getDomData(node);
if (context) { return context; }
if (node.parentNode) { return kv.utils.contextFor(node.parentNode); }
break;
}
return undefined;
},
isEmptyVal: function (val) {
if (val === undefined) {
return true;
}
if (val === null) {
return true;
}
if (val === "") {
return true;
}
},
getOriginalElementTitle: function (element) {
var savedOriginalTitle = kv.utils.getAttribute(element, 'data-orig-title'),
currentTitle = element.title,
hasSavedOriginalTitle = kv.utils.hasAttribute(element, 'data-orig-title');
return hasSavedOriginalTitle ?
savedOriginalTitle : currentTitle;
},
async: function (expr) {
if (window.setImmediate) { window.setImmediate(expr); }
else { window.setTimeout(expr, 0); }
},
forEach: function (object, callback) {
if (kv.utils.isArray(object)) {
return forEach(object, callback);
}
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
callback(object[prop], prop);
}
}
}
};
}());;var api = (function () {
var isInitialized = 0,
configuration = kv.configuration,
utils = kv.utils;
function cleanUpSubscriptions(context) {
forEach(context.subscriptions, function (subscription) {
subscription.dispose();
});
context.subscriptions = [];
}
function dispose(context) {
if (context.options.deep) {
forEach(context.flagged, function (obj) {
delete obj.__kv_traversed;
});
context.flagged.length = 0;
}
if (!context.options.live) {
cleanUpSubscriptions(context);
}
}
function runTraversal(obj, context) {
context.validatables = [];
cleanUpSubscriptions(context);
traverseGraph(obj, context);
dispose(context);
}
function traverseGraph(obj, context, level) {
var objValues = [],
val = obj.peek ? obj.peek() : obj;
if (obj.__kv_traversed === true) {
return;
}
if (context.options.deep) {
obj.__kv_traversed = true;
context.flagged.push(obj);
}
//default level value depends on deep option.
level = (level !== undefined ? level : context.options.deep ? 1 : -1);
// if object is observable then add it to the list
if (ko.isObservable(obj)) {
// ensure it's validatable but don't extend validatedObservable because it
// would overwrite isValid property.
if (!obj.errors && !utils.isValidatable(obj)) {
obj.extend({ validatable: true });
}
context.validatables.push(obj);
if (context.options.live && utils.isObservableArray(obj)) {
context.subscriptions.push(obj.subscribe(function () {
context.graphMonitor.valueHasMutated();
}));
}
}
//get list of values either from array or object but ignore non-objects
// and destroyed objects
if (val && !val._destroy) {
if (utils.isArray(val)) {
objValues = val;
}
else if (utils.isObject(val)) {
objValues = utils.values(val);
}
}
//process recursively if it is deep grouping
if (level !== 0) {
utils.forEach(objValues, function (observable) {
//but not falsy things and not HTML Elements
if (observable && !observable.nodeType && (!ko.isComputed(observable) || observable.rules)) {
traverseGraph(observable, context, level + 1);
}
});
}
}
function collectErrors(array) {
var errors = [];
forEach(array, function (observable) {
// Do not collect validatedObservable errors
if (utils.isValidatable(observable) && !observable.isValid()) {
// Use peek because we don't want a dependency for 'error' property because it
// changes before 'isValid' does. (Issue #99)
errors.push(observable.error.peek());
}
});
return errors;
}
return {
//Call this on startup
//any config can be overridden with the passed in options
init: function (options, force) {
//done run this multiple times if we don't really want to
if (isInitialized > 0 && !force) {
return;
}
//because we will be accessing options properties it has to be an object at least
options = options || {};
//if specific error classes are not provided then apply generic errorClass
//it has to be done on option so that options.errorClass can override default
//errorElementClass and errorMessage class but not those provided in options
options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass;
options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass;
extend(configuration, options);
if (configuration.registerExtenders) {
kv.registerExtenders();
}
isInitialized = 1;
},
// resets the config back to its original state
reset: kv.configuration.reset,
// recursively walks a viewModel and creates an object that
// provides validation information for the entire viewModel
// obj -> the viewModel to walk
// options -> {
// deep: false, // if true, will walk past the first level of viewModel properties
// observable: false // if true, returns a computed observable indicating if the viewModel is valid
// }
group: function group(obj, options) { // array of observables or viewModel
options = extend(extend({}, configuration.grouping), options);
var context = {
options: options,
graphMonitor: ko.observable(),
flagged: [],
subscriptions: [],
validatables: []
};
var result = null;
//if using observables then traverse structure once and add observables
if (options.observable) {
result = ko.computed(function () {
context.graphMonitor(); //register dependency
runTraversal(obj, context);
return collectErrors(context.validatables);
});
}
else { //if not using observables then every call to error() should traverse the structure
result = function () {
runTraversal(obj, context);
return collectErrors(context.validatables);
};
}
result.showAllMessages = function (show) { // thanks @heliosPortal
if (show === undefined) {//default to true
show = true;
}
result.forEach(function (observable) {
if (utils.isValidatable(observable)) {
observable.isModified(show);
}
});
};
result.isAnyMessageShown = function () {
var invalidAndModifiedPresent;
invalidAndModifiedPresent = !!result.find(function (observable) {
return utils.isValidatable(observable) && !observable.isValid() && observable.isModified();
});
return invalidAndModifiedPresent;
};
result.filter = function(predicate) {
predicate = predicate || function () { return true; };
// ensure we have latest changes
result();
return koUtils.arrayFilter(context.validatables, predicate);
};
result.find = function(predicate) {
predicate = predicate || function () { return true; };
// ensure we have latest changes
result();
return koUtils.arrayFirst(context.validatables, predicate);
};
result.forEach = function(callback) {
callback = callback || function () { };
// ensure we have latest changes
result();
forEach(context.validatables, callback);
};
result.map = function(mapping) {
mapping = mapping || function (item) { return item; };
// ensure we have latest changes
result();
return koUtils.arrayMap(context.validatables, mapping);
};
/**
* @private You should not rely on this method being here.
* It's a private method and it may change in the future.
*
* @description Updates the validated object and collects errors from it.
*/
result._updateState = function(newValue) {
if (!utils.isObject(newValue)) {
throw new Error('An object is required.');
}
obj = newValue;
if (options.observable) {
context.graphMonitor.valueHasMutated();
}
else {
runTraversal(newValue, context);
return collectErrors(context.validatables);
}
};
return result;
},
formatMessage: function (message, params, observable) {
if (utils.isObject(params) && params.typeAttr) {
params = params.value;
}
if (typeof message === 'function') {
return message(params, observable);
}
var replacements = unwrap(params);
if (replacements == null) {
replacements = [];
}
if (!utils.isArray(replacements)) {
replacements = [replacements];
}
return message.replace(/{(\d+)}/gi, function(match, index) {
if (typeof replacements[index] !== 'undefined') {
return replacements[index];
}
return match;
});
},
// addRule:
// This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator
// ie: kv.addRule(myObservable, {
// rule: 'required',
// params: true
// });
//
addRule: function (observable, rule) {
observable.extend({ validatable: true });
var hasRule = !!koUtils.arrayFirst(observable.rules(), function(item) {
return item.rule && item.rule === rule.rule;
});
if (!hasRule) {
//push a Rule Context to the observables local array of Rule Contexts
observable.rules.push(rule);
}
return observable;
},
// addAnonymousRule:
// Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property
// and developers typically are wanting to add them on the fly or not register a rule with the 'kv.rules' object
//
// Example:
// var test = ko.observable('something').extend{(
// validation: {
// validator: function(val, someOtherVal){
// return true;
// },
// message: "Something must be really wrong!',
// params: true
// }
// )};
addAnonymousRule: function (observable, ruleObj) {
if (ruleObj['message'] === undefined) {
ruleObj['message'] = 'Error';
}
//make sure onlyIf is honoured
if (ruleObj.onlyIf) {
ruleObj.condition = ruleObj.onlyIf;
}
//add the anonymous rule to the observable
kv.addRule(observable, ruleObj);
},
addExtender: function (ruleName) {
ko.extenders[ruleName] = function (observable, params) {
//params can come in a few flavors
// 1. Just the params to be passed to the validator
// 2. An object containing the Message to be used and the Params to pass to the validator
// 3. A condition when the validation rule to be applied
//
// Example:
// var test = ko.observable(3).extend({
// max: {
// message: 'This special field has a Max of {0}',
// params: 2,
// onlyIf: function() {
// return specialField.IsVisible();
// }
// }
// )};
//
if (params && (params.message || params.onlyIf)) { //if it has a message or condition object, then its an object literal to use
return kv.addRule(observable, {
rule: ruleName,
message: params.message,
params: utils.isEmptyVal(params.params) ? true : params.params,
condition: params.onlyIf
});
} else {
return kv.addRule(observable, {
rule: ruleName,
params: params
});
}
};
},
// loops through all kv.rules and adds them as extenders to
// ko.extenders
registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts
if (configuration.registerExtenders) {
for (var ruleName in kv.rules) {
if (kv.rules.hasOwnProperty(ruleName)) {
if (!ko.extenders[ruleName]) {
kv.addExtender(ruleName);
}
}
}
}
},
//creates a span next to the @element with the specified error class
insertValidationMessage: function (element) {
var span = document.createElement('SPAN');
span.className = utils.getConfigOptions(element).errorMessageClass;
utils.insertAfter(element, span);
return span;
},
// if html-5 validation attributes have been specified, this parses
// the attributes on @element
parseInputValidationAttributes: function (element, valueAccessor) {
forEach(kv.configuration.html5Attributes, function (attr) {
if (utils.hasAttribute(element, attr)) {
var params = element.getAttribute(attr) || true;
if (attr === 'min' || attr === 'max')
{
// If we're validating based on the min and max attributes, we'll
// need to know what the 'type' attribute is set to
var typeAttr = element.getAttribute('type');
if (typeof typeAttr === "undefined" || !typeAttr)
{
// From http://www.w3.org/TR/html-markup/input:
// An input element with no type attribute specified represents the
// same thing as an input element with its type attribute set to "text".
typeAttr = "text";
}
params = {typeAttr: typeAttr, value: params};
}
kv.addRule(valueAccessor(), {
rule: attr,
params: params
});
}
});
var currentType = element.getAttribute('type');
forEach(kv.configuration.html5InputTypes, function (type) {
if (type === currentType) {
kv.addRule(valueAccessor(), {
rule: (type === 'date') ? 'dateISO' : type,
params: true
});
}
});
},
// writes html5 validation attributes on the element passed in
writeInputValidationAttributes: function (element, valueAccessor) {
var observable = valueAccessor();
if (!observable || !observable.rules) {
return;
}
var contexts = observable.rules(); // observable array
// loop through the attributes and add the information needed
forEach(kv.configuration.html5Attributes, function (attr) {
var ctx = koUtils.arrayFirst(contexts, function (ctx) {
return ctx.rule && ctx.rule.toLowerCase() === attr.toLowerCase();
});
if (!ctx) {
return;
}
// we have a rule matching a validation attribute at this point
// so lets add it to the element along with the params
ko.computed({
read: function() {
var params = ko.unwrap(ctx.params);
// we have to do some special things for the pattern validation
if (ctx.rule === "pattern" && params instanceof RegExp) {
// we need the pure string representation of the RegExpr without the //gi stuff
params = params.source;
}
element.setAttribute(attr, params);
},
disposeWhenNodeIsRemoved: element
});
});
contexts = null;
},
//take an existing binding handler and make it cause automatic validations
makeBindingHandlerValidatable: function (handlerName) {
var init = ko.bindingHandlers[handlerName].init;
ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
};
},
// visit an objects properties and apply validation rules from a definition
setRules: function (target, definition) {
var setRules = function (target, definition) {
if (!target || !definition) { return; }
for (var prop in definition) {
if (!definition.hasOwnProperty(prop)) { continue; }
var ruleDefinitions = definition[prop];
//check the target property exists and has a value
if (!target[prop]) { continue; }
var targetValue = target[prop],
unwrappedTargetValue = unwrap(targetValue),
rules = {},
nonRules = {};
for (var rule in ruleDefinitions) {
if (!ruleDefinitions.hasOwnProperty(rule)) { continue; }
if (kv.rules[rule]) {
rules[rule] = ruleDefinitions[rule];
} else {
nonRules[rule] = ruleDefinitions[rule];
}
}
//apply rules
if (ko.isObservable(targetValue)) {
targetValue.extend(rules);
}
//then apply child rules
//if it's an array, apply rules to all children
if (unwrappedTargetValue && utils.isArray(unwrappedTargetValue)) {
for (var i = 0; i < unwrappedTargetValue.length; i++) {
setRules(unwrappedTargetValue[i], nonRules);
}
//otherwise, just apply to this property
} else {
setRules(unwrappedTargetValue, nonRules);
}
}
};
setRules(target, definition);
}
};
}());
// expose api publicly
extend(ko.validation, api);
;//Validation Rules:
// You can view and override messages or rules via:
// kv.rules[ruleName]
//
// To implement a custom Rule, simply use this template:
// kv.rules['<custom rule name>'] = {
// validator: function (val, param) {
// <custom logic>
// return <true or false>;
// },
// message: '<custom validation message>' //optionally you can also use a '{0}' to denote a placeholder that will be replaced with your 'param'
// };
//
// Example:
// kv.rules['mustEqual'] = {
// validator: function( val, mustEqualVal ){
// return val === mustEqualVal;
// },
// message: 'This field must equal {0}'
// };
//
kv.rules = {};
kv.rules['required'] = {
validator: function (val, required) {
var testVal;
if (val === undefined || val === null) {
return !required;
}
testVal = val;
if (typeof (val) === 'string') {
if (String.prototype.trim) {
testVal = val.trim();
}
else {
testVal = val.replace(/^\s+|\s+$/g, '');
}
}
if (!required) {// if they passed: { required: false }, then don't require this
return true;
}
return ((testVal + '').length > 0);
},
message: 'This field is required.'
};
function minMaxValidatorFactory(validatorName) {
var isMaxValidation = validatorName === "max";
return function (val, options) {
if (kv.utils.isEmptyVal(val)) {
return true;
}
var comparisonValue, type;
if (options.typeAttr === undefined) {
// This validator is being called from javascript rather than
// being bound from markup
type = "text";
comparisonValue = options;
} else {
type = options.typeAttr;
comparisonValue = options.value;
}
// From http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-min,
// if the value is parseable to a number, then the minimum should be numeric
if (!isNaN(comparisonValue) && !(comparisonValue instanceof Date)) {
type = "number";
}
var regex, valMatches, comparisonValueMatches;
switch (type.toLowerCase()) {
case "week":
regex = /^(\d{4})-W(\d{2})$/;
valMatches = val.match(regex);
if (valMatches === null) {
throw new Error("Invalid value for " + validatorName + " attribute for week input. Should look like " +
"'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min");
}
comparisonValueMatches = comparisonValue.match(regex);
// If no regex matches were found, validation fails
if (!comparisonValueMatches) {
return false;
}
if (isMaxValidation) {
return (valMatches[1] < comparisonValueMatches[1]) || // older year
// same year, older week
((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2]));
} else {
return (valMatches[1] > comparisonValueMatches[1]) || // newer year
// same year, newer week
((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2]));
}
break;
case "month":
regex = /^(\d{4})-(\d{2})$/;
valMatches = val.match(regex);
if (valMatches === null) {
throw new Error("Invalid value for " + validatorName + " attribute for month input. Should look like " +
"'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min");
}
comparisonValueMatches = comparisonValue.match(regex);
// If no regex matches were found, validation fails
if (!comparisonValueMatches) {
return false;
}
if (isMaxValidation) {
return ((valMatches[1] < comparisonValueMatches[1]) || // older year
// same year, older month
((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2])));
} else {
return (valMatches[1] > comparisonValueMatches[1]) || // newer year
// same year, newer month
((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2]));
}
break;
case "number":
case "range":
if (isMaxValidation) {
return (!isNaN(val) && parseFloat(val) <= parseFloat(comparisonValue));
} else {
return (!isNaN(val) && parseFloat(val) >= parseFloat(comparisonValue));
}
break;
default:
if (isMaxValidation) {
return val <= comparisonValue;
} else {
return val >= comparisonValue;
}
}
};
}
kv.rules['min'] = {
validator: minMaxValidatorFactory("min"),
message: 'Please enter a value greater than or equal to {0}.'
};
kv.rules['max'] = {
validator: minMaxValidatorFactory("max"),
message: 'Please enter a value less than or equal to {0}.'
};
kv.rules['minLength'] = {
validator: function (val, minLength) {
if(kv.utils.isEmptyVal(val)) { return true; }
var normalizedVal = kv.utils.isNumber(val) ? ('' + val) : val;
return normalizedVal.length >= minLength;
},
message: 'Please enter at least {0} characters.'
};
kv.rules['maxLength'] = {
validator: function (val, maxLength) {
if(kv.utils.isEmptyVal(val)) { return true; }
var normalizedVal = kv.utils.isNumber(val) ? ('' + val) : val;
return normalizedVal.length <= maxLength;
},
message: 'Please enter no more than {0} characters.'
};
kv.rules['pattern'] = {
validator: function (val, regex) {
return kv.utils.isEmptyVal(val) || val.toString().match(regex) !== null;
},
message: 'Please check this value.'
};
kv.rules['step'] = {
validator: function (val, step) {
// in order to handle steps of .1 & .01 etc.. Modulus won't work
// if the value is a decimal, so we have to correct for that
if (kv.utils.isEmptyVal(val) || step === 'any') { return true; }
var dif = (val * 100) % (step * 100);
return Math.abs(dif) < 0.00001 || Math.abs(1 - dif) < 0.00001;
},
message: 'The value must increment by {0}.'
};
kv.rules['email'] = {
validator: function (val, validate) {
if (!validate) { return true; }
//I think an empty email address is also a valid entry
//if one want's to enforce entry it should be done with 'required: true'
return kv.utils.isEmptyVal(val) || (
// jquery validate regex - thanks Scott Gonzalez
validate && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(val)
);
},
message: 'Please enter a proper email address.'
};
kv.rules['date'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return kv.utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value)));
},
message: 'Please enter a proper date.'
};
kv.rules['dateISO'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return kv.utils.isEmptyVal(value) || (validate && /^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(value));
},
message: 'Please enter a proper date.'
};
kv.rules['number'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return kv.utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value));
},
message: 'Please enter a number.'
};
kv.rules['digit'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return kv.utils.isEmptyVal(value) || (validate && /^\d+$/.test(value));
},
message: 'Please enter a digit.'
};
kv.rules['phoneUS'] = {
validator: function (phoneNumber, validate) {
if (!validate) { return true; }
if (kv.utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required
if (typeof (phoneNumber) !== 'string') { return false; }
phoneNumber = phoneNumber.replace(/\s+/g, "");
return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
},
message: 'Please specify a valid phone number.'
};
kv.rules['equal'] = {
validator: function (val, params) {
var otherValue = params;
return val === kv.utils.getValue(otherValue);
},
message: 'Values must equal.'
};
kv.rules['notEqual'] = {
validator: function (val, params) {
var otherValue = params;
return val !== kv.utils.getValue(otherValue);
},
message: 'Please choose another value.'
};
//unique in collection
// options are:
// collection: array or function returning (observable) array
// in which the value has to be unique
// valueAccessor: function that returns value from an object stored in collection
// if it is null the value is compared directly
// external: set to true when object you are validating is automatically updating collection
kv.rules['unique'] = {
validator: function (val, options) {
var c = kv.utils.getValue(options.collection),
external = kv.utils.getValue(options.externalValue),
counter = 0;
if (!val || !c) { return true; }
koUtils.arrayFilter(c, function (item) {
if (val === (options.valueAccessor ? options.valueAccessor(item) : item)) { counter++; }
});
// if value is external even 1 same value in collection means the value is not unique
return counter < (!!external ? 1 : 2);
},
message: 'Please make sure the value is unique.'
};
//now register all of these!
(function () {
kv.registerExtenders();
}());
;// The core binding handler
// this allows us to setup any value binding that internally always
// performs the same functionality
ko.bindingHandlers['validationCore'] = (function () {
return {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var config = kv.utils.getConfigOptions(element);
var observable = valueAccessor();
// parse html5 input validation attributes, optional feature
if (config.parseInputAttributes) {
kv.utils.async(function () { kv.parseInputValidationAttributes(element, valueAccessor); });
}
// if requested insert message element and apply bindings
if (config.insertMessages && kv.utils.isValidatable(observable)) {
// insert the <span></span>
var validationMessageElement = kv.insertValidationMessage(element);
// if we're told to use a template, make sure that gets rendered
if (config.messageTemplate) {
ko.renderTemplate(config.messageTemplate, { field: observable }, null, validationMessageElement, 'replaceNode');
} else {
ko.applyBindingsToNode(validationMessageElement, { validationMessage: observable });
}
}
// write the html5 attributes if indicated by the config
if (config.writeInputAttributes && kv.utils.isValidatable(observable)) {
kv.writeInputValidationAttributes(element, valueAccessor);
}
// if requested, add binding to decorate element
if (config.decorateInputElement && kv.utils.isValidatable(observable)) {
ko.applyBindingsToNode(element, { validationElement: observable });
}
}
};
}());
// override for KO's default 'value', 'checked', 'textInput' and selectedOptions bindings
kv.makeBindingHandlerValidatable("value");
kv.makeBindingHandlerValidatable("checked");
if (ko.bindingHandlers.textInput) {
kv.makeBindingHandlerValidatable("textInput");
}
kv.makeBindingHandlerValidatable("selectedOptions");
ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding
update: function (element, valueAccessor) {
var obsv = valueAccessor(),
config = kv.utils.getConfigOptions(element),
val = unwrap(obsv),
msg = null,
isModified = false,
isValid = false;
if (obsv === null || typeof obsv === 'undefined') {
throw new Error('Cannot bind validationMessage to undefined value. data-bind expression: ' +
element.getAttribute('data-bind'));
}
isModified = obsv.isModified && obsv.isModified();
isValid = obsv.isValid && obsv.isValid();
var error = null;
if (!config.messagesOnModified || isModified) {
error = isValid ? null : obsv.error;
}
var isVisible = !config.messagesOnModified || isModified ? !isValid : false;
var isCurrentlyVisible = element.style.display !== "none";
if (config.allowHtmlMessages) {
koUtils.setHtml(element, error);
} else {
ko.bindingHandlers.text.update(element, function () { return error; });
}
if (isCurrentlyVisible && !isVisible) {
element.style.display = 'none';
} else if (!isCurrentlyVisible && isVisible) {
element.style.display = '';
}
}
};
ko.bindingHandlers['validationElement'] = {
update: function (element, valueAccessor, allBindingsAccessor) {
var obsv = valueAccessor(),
config = kv.utils.getConfigOptions(element),
val = unwrap(obsv),
msg = null,
isModified = false,
isValid = false;
if (obsv === null || typeof obsv === 'undefined') {
throw new Error('Cannot bind validationElement to undefined value. data-bind expression: ' +
element.getAttribute('data-bind'));
}
isModified = obsv.isModified && obsv.isModified();
isValid = obsv.isValid && obsv.isValid();
// create an evaluator function that will return something like:
// css: { validationElement: true }
var cssSettingsAccessor = function () {
var css = {};
var shouldShow = ((!config.decorateElementOnModified || isModified) ? !isValid : false);
// css: { validationElement: false }
css[config.errorElementClass] = shouldShow;
return css;
};
//add or remove class on the element;
ko.bindingHandlers.css.update(element, cssSettingsAccessor, allBindingsAccessor);
if (!config.errorsAsTitle) { return; }
ko.bindingHandlers.attr.update(element, function () {
var
hasModification = !config.errorsAsTitleOnModified || isModified,
title = kv.utils.getOriginalElementTitle(element);
if (hasModification && !isValid) {
return { title: obsv.error, 'data-orig-title': title };
} else if (!hasModification || isValid) {
return { title: title, 'data-orig-title': null };
}
});
}
};
// ValidationOptions:
// This binding handler allows you to override the initial config by setting any of the options for a specific element or context of elements
//
// Example:
// <div data-bind="validationOptions: { insertMessages: true, messageTemplate: 'customTemplate', errorMessageClass: 'mySpecialClass'}">
// <input type="text" data-bind="value: someValue"/>
// <input type="text" data-bind="value: someValue2"/>
// </div>
ko.bindingHandlers['validationOptions'] = (function () {
return {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = unwrap(valueAccessor());
if (options) {
var newConfig = extend({}, kv.configuration);
extend(newConfig, options);
//store the validation options on the node so we can retrieve it later
kv.utils.setDomData(element, newConfig);
}
}
};
}());
;// Validation Extender:
// This is for creating custom validation logic on the fly
// Example:
// var test = ko.observable('something').extend{(
// validation: {
// validator: function(val, someOtherVal){
// return true;
// },
// message: "Something must be really wrong!',
// params: true
// }
// )};
ko.extenders['validation'] = function (observable, rules) { // allow single rule or array
forEach(kv.utils.isArray(rules) ? rules : [rules], function (rule) {
// the 'rule' being passed in here has no name to identify a core Rule,
// so we add it as an anonymous rule
// If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples
kv.addAnonymousRule(observable, rule);
});
return observable;
};
//This is the extender that makes a Knockout Observable also 'Validatable'
//examples include:
// 1. var test = ko.observable('something').extend({validatable: true});
// this will ensure that the Observable object is setup properly to respond to rules
//
// 2. test.extend({validatable: false});
// this will remove the validation properties from the Observable object should you need to do that.
ko.extenders['validatable'] = function (observable, options) {
if (!kv.utils.isObject(options)) {
options = { enable: options };
}
if (!('enable' in options)) {
options.enable = true;
}
if (options.enable && !kv.utils.isValidatable(observable)) {
var config = kv.configuration.validate || {};
var validationOptions = {
throttleEvaluation : options.throttle || config.throttle
};
observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid
// observable.rules:
// ObservableArray of Rule Contexts, where a Rule Context is simply the name of a rule and the params to supply to it
//
// Rule Context = { rule: '<rule name>', params: '<passed in params>', message: '<Override of default Message>' }
observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation
//in case async validation is occurring
observable.isValidating = ko.observable(false);
//the true holder of whether the observable is valid or not
observable.__valid__ = ko.observable(true);
observable.isModified = ko.observable(false);
// a semi-protected observable
observable.isValid = ko.computed(observable.__valid__);
//manually set error state
observable.setError = function (error) {
var previousError = observable.error.peek();
var previousIsValid = observable.__valid__.peek();
observable.error(error);
observable.__valid__(false);
if (previousError !== error && !previousIsValid) {
// if the observable was not valid before then isValid will not mutate,
// hence causing any grouping to not display the latest error.
observable.isValid.notifySubscribers();
}
};
//manually clear error state
observable.clearError = function () {
observable.error(null);
observable.__valid__(true);
return observable;
};
//subscribe to changes in the observable
var h_change = observable.subscribe(function () {
observable.isModified(true);
});
// we use a computed here to ensure that anytime a dependency changes, the
// validation logic evaluates
var h_obsValidationTrigger = ko.computed(extend({
read: function () {
var obs = observable(),
ruleContexts = observable.rules();
kv.validateObservable(observable);
return true;
}
}, validationOptions));
extend(h_obsValidationTrigger, validationOptions);
observable._disposeValidation = function () {
//first dispose of the subscriptions
observable.isValid.dispose();
observable.rules.removeAll();
h_change.dispose();
h_obsValidationTrigger.dispose();
delete observable['rules'];
delete observable['error'];
delete observable['isValid'];
delete observable['isValidating'];
delete observable['__valid__'];
delete observable['isModified'];
delete observable['setError'];
delete observable['clearError'];
delete observable['_disposeValidation'];
};
} else if (options.enable === false && observable._disposeValidation) {
observable._disposeValidation();
}
return observable;
};
function validateSync(observable, rule, ctx) {
//Execute the validator and see if its valid
if (!rule.validator(observable(), (ctx.params === undefined ? true : unwrap(ctx.params)))) { // default param is true, eg. required = true
//not valid, so format the error message and stick it in the 'error' variable
observable.setError(kv.formatMessage(
ctx.message || rule.message,
unwrap(ctx.params),
observable));
return false;
} else {
return true;
}
}
function validateAsync(observable, rule, ctx) {
observable.isValidating(true);
var callBack = function (valObj) {
var isValid = false,
msg = '';
if (!observable.__valid__()) {
// since we're returning early, make sure we turn this off
observable.isValidating(false);
return; //if its already NOT valid, don't add to that
}
//we were handed back a complex object
if (valObj['message']) {
isValid = valObj.isValid;
msg = valObj.message;
} else {
isValid = valObj;
}
if (!isValid) {
//not valid, so format the error message and stick it in the 'error' variable
observable.error(kv.formatMessage(
msg || ctx.message || rule.message,
unwrap(ctx.params),
observable));
observable.__valid__(isValid);
}
// tell it that we're done
observable.isValidating(false);
};
kv.utils.async(function() {
//fire the validator and hand it the callback
rule.validator(observable(), ctx.params === undefined ? true : unwrap(ctx.params), callBack);
});
}
kv.validateObservable = function (observable) {
var i = 0,
rule, // the rule validator to execute
ctx, // the current Rule Context for the loop
ruleContexts = observable.rules(), //cache for iterator
len = ruleContexts.length; //cache for iterator
for (; i < len; i++) {
//get the Rule Context info to give to the core Rule
ctx = ruleContexts[i];
// checks an 'onlyIf' condition
if (ctx.condition && !ctx.condition()) {
continue;
}
//get the core Rule to use for validation
rule = ctx.rule ? kv.rules[ctx.rule] : ctx;
if (rule['async'] || ctx['async']) {
//run async validation
validateAsync(observable, rule, ctx);
} else {
//run normal sync validation
if (!validateSync(observable, rule, ctx)) {
return false; //break out of the loop
}
}
}
//finally if we got this far, make the observable valid again!
observable.clearError();
return true;
};
;
var _locales = {};
var _currentLocale;
kv.defineLocale = function(name, values) {
if (name && values) {
_locales[name.toLowerCase()] = values;
return values;
}
return null;
};
kv.locale = function(name) {
if (name) {
name = name.toLowerCase();
if (_locales.hasOwnProperty(name)) {
kv.localize(_locales[name]);
_currentLocale = name;
}
else {
throw new Error('Localization ' + name + ' has not been loaded.');
}
}
return _currentLocale;
};
//quick function to override rule messages
kv.localize = function (msgTranslations) {
var rules = kv.rules;
//loop the properties in the object and assign the msg to the rule
for (var ruleName in msgTranslations) {
if (rules.hasOwnProperty(ruleName)) {
rules[ruleName].message = msgTranslations[ruleName];
}
}
};
// Populate default locale (this will make en-US.js somewhat redundant)
(function() {
var localeData = {};
var rules = kv.rules;
for (var ruleName in rules) {
if (rules.hasOwnProperty(ruleName)) {
localeData[ruleName] = rules[ruleName].message;
}
}
kv.defineLocale('en-us', localeData);
})();
// No need to invoke locale because the messages are already defined along with the rules for en-US
_currentLocale = 'en-us';
;/**
* Possible invocations:
* applyBindingsWithValidation(viewModel)
* applyBindingsWithValidation(viewModel, options)
* applyBindingsWithValidation(viewModel, rootNode)
* applyBindingsWithValidation(viewModel, rootNode, options)
*/
ko.applyBindingsWithValidation = function (viewModel, rootNode, options) {
var node = document.body,
config;
if (rootNode && rootNode.nodeType) {
node = rootNode;
config = options;
}
else {
config = rootNode;
}
kv.init();
if (config) {
config = extend(extend({}, kv.configuration), config);
kv.utils.setDomData(node, config);
}
ko.applyBindings(viewModel, node);
};
//override the original applyBindings so that we can ensure all new rules and what not are correctly registered
var origApplyBindings = ko.applyBindings;
ko.applyBindings = function (viewModel, rootNode) {
kv.init();
origApplyBindings(viewModel, rootNode);
};
ko.validatedObservable = function (initialValue, options) {
if (!options && !kv.utils.isObject(initialValue)) {
return ko.observable(initialValue).extend({ validatable: true });
}
var obsv = ko.observable(initialValue);
obsv.errors = kv.group(kv.utils.isObject(initialValue) ? initialValue : {}, options);
obsv.isValid = ko.observable(obsv.errors().length === 0);
if (ko.isObservable(obsv.errors)) {
obsv.errors.subscribe(function(errors) {
obsv.isValid(errors.length === 0);
});
}
else {
ko.computed(obsv.errors).subscribe(function (errors) {
obsv.isValid(errors.length === 0);
});
}
obsv.subscribe(function(newValue) {
if (!kv.utils.isObject(newValue)) {
/*
* The validation group works on objects.
* Since the new value is a primitive (scalar, null or undefined) we need
* to create an empty object to pass along.
*/
newValue = {};
}
// Force the group to refresh
obsv.errors._updateState(newValue);
obsv.isValid(obsv.errors().length === 0);
});
return obsv;
};
;})); |
src/routes/Maps/containers/Container.js | dingchaoyan1983/ReactRedux | import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux'
import classnames from 'classnames';
import { fetchMapData } from '../modules/reducer';
import _get from 'lodash/object/get';
import css from './maps.css';
import GoogleMap from 'components/GoogleMap';
import Mapsliderbar from 'components/Maps/Mapsliderbar';
import MapTypeSelector from 'components/Maps/MapTypeSelector';
const mapStateToProps = (state) => {
return {
maps: state.maps
}
}
const mapDispatchToProps = () => {
return {
fetchMapData
}
}
@connect(mapStateToProps, mapDispatchToProps)
export default class Maps extends React.Component {
render () {
let isLoading = _get(this.props, 'maps.meta.isLoading');
return (
<div className={classnames(css.container, isLoading ? 'loading-overlay' : '')}>
<GoogleMap ref="googleMap" {...this.props}>
<Mapsliderbar>
<header className={css.layers}>
<MapTypeSelector {...this.props}/>
</header>
</Mapsliderbar>
</GoogleMap>
</div>
)
}
}
|
admin/client/Signin/index.js | concoursbyappointment/keystoneRedux | /**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import qs from 'qs';
import React from 'react';
import ReactDOM from 'react-dom';
import Signin from './Signin';
const params = qs.parse(window.location.search.replace(/^\?/, ''));
const from = typeof params.from === 'string' && params.from.charAt(0) === '/'
? params.from : undefined;
ReactDOM.render(
<Signin
brand={Keystone.brand}
from={from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
actor-apps/app-web/src/app/components/modals/Contacts.react.js | hejunbinlan/actor-platform | //
// Deprecated
//
import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import ContactStore from 'stores/ContactStore';
import Modal from 'react-modal';
import AvatarItem from 'components/common/AvatarItem.react';
let appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
let getStateFromStores = () => {
return {
contacts: ContactStore.getContacts(),
isShown: ContactStore.isContactsOpen()
};
};
class Contacts extends React.Component {
componentWillMount() {
ContactStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ContactStore.removeChangeListener(this._onChange);
}
constructor() {
super();
this._onClose = this._onClose.bind(this);
this._onChange = this._onChange.bind(this);
this.state = getStateFromStores();
}
_onChange() {
this.setState(getStateFromStores());
}
_onClose() {
ContactActionCreators.hideContactList();
}
render() {
let contacts = this.state.contacts;
let isShown = this.state.isShown;
let contactList = _.map(contacts, (contact, i) => {
return (
<Contacts.ContactItem contact={contact} key={i}/>
);
});
if (contacts !== null) {
return (
<Modal className="modal contacts"
closeTimeoutMS={150}
isOpen={isShown}>
<header className="modal__header">
<a className="modal__header__close material-icons" onClick={this._onClose}>clear</a>
<h3>Contact list</h3>
</header>
<div className="modal__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
} else {
return (null);
}
}
}
Contacts.ContactItem = React.createClass({
propTypes: {
contact: React.PropTypes.object
},
mixins: [PureRenderMixin],
_openNewPrivateCoversation() {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
ContactActionCreators.hideContactList();
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a>
</div>
</li>
);
}
});
export default Contacts;
|
ajax/libs/webshim/1.15.3/dev/shims/es6.js | athanclark/cdnjs | // ES6-shim 0.15.0 (c) 2013-2014 Paul Miller (http://paulmillr.com)
// ES6-shim may be freely distributed under the MIT license.
// For more details and documentation:
// https://github.com/paulmillr/es6-shim/
webshim.register('es6', function($, webshim, window, document, undefined){
'use strict';
var isCallableWithoutNew = function(func) {
try { func(); }
catch (e) { return false; }
return true;
};
var supportsSubclassing = function(C, f) {
/* jshint proto:true */
try {
var Sub = function() { C.apply(this, arguments); };
if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ }
Object.setPrototypeOf(Sub, C);
Sub.prototype = Object.create(C.prototype, {
constructor: { value: C }
});
return f(Sub);
} catch (e) {
return false;
}
};
var arePropertyDescriptorsSupported = function() {
try {
Object.defineProperty({}, 'x', {});
return true;
} catch (e) { /* this is IE 8. */
return false;
}
};
var startsWithRejectsRegex = function() {
var rejectsRegex = false;
if (String.prototype.startsWith) {
try {
'/a/'.startsWith(/a/);
} catch (e) { /* this is spec compliant */
rejectsRegex = true;
}
}
return rejectsRegex;
};
/*jshint evil: true */
var getGlobal = new Function('return this;');
/*jshint evil: false */
var main = function() {
var globals = getGlobal();
var global_isFinite = globals.isFinite;
var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported();
var startsWithIsCompliant = startsWithRejectsRegex();
var _slice = Array.prototype.slice;
var _indexOf = String.prototype.indexOf;
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var ArrayIterator; // make our implementation private
// Define configurable, writable and non-enumerable props
// if they don’t exist.
var defineProperties = function(object, map) {
Object.keys(map).forEach(function(name) {
var method = map[name];
if (name in object) return;
if (supportsDescriptors) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
} else {
object[name] = method;
}
});
};
// Simple shim for Object.create on ES3 browsers
// (unlike real shim, no attempt to support `prototype === null`)
var create = Object.create || function(prototype, properties) {
function Type() {}
Type.prototype = prototype;
var object = new Type();
if (typeof properties !== "undefined") {
defineProperties(object, properties);
}
return object;
};
// This is a private name in the es6 spec, equal to '[Symbol.iterator]'
// we're going to use an arbitrary _-prefixed name to make our shims
// work properly with each other, even though we don't have full Iterator
// support. That is, `Array.from(map.keys())` will work, but we don't
// pretend to export a "real" Iterator interface.
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var addIterator = function(prototype, impl) {
if (!impl) { impl = function iterator() { return this; }; }
var o = {};
o[$iterator$] = impl;
defineProperties(prototype, o);
};
// taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
// can be replaced with require('is-arguments') if we ever use a build process instead
var isArguments = function isArguments(value) {
var str = _toString.call(value);
var result = str === '[object Arguments]';
if (!result) {
result = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
_toString.call(value.callee) === '[object Function]';
}
return result;
};
var emulateES6construct = function(o) {
if (!ES.TypeIsObject(o)) throw new TypeError('bad object');
// es5 approximation to es6 subclass semantics: in es6, 'new Foo'
// would invoke Foo.@@create to allocation/initialize the new object.
// In es5 we just get the plain object. So if we detect an
// uninitialized object, invoke o.constructor.@@create
if (!o._es6construct) {
if (o.constructor && ES.IsCallable(o.constructor['@@create'])) {
o = o.constructor['@@create'](o);
}
defineProperties(o, { _es6construct: true });
}
return o;
};
var ES = {
CheckObjectCoercible: function(x, optMessage) {
/* jshint eqnull:true */
if (x == null)
throw new TypeError(optMessage || ('Cannot call method on ' + x));
return x;
},
TypeIsObject: function(x) {
/* jshint eqnull:true */
// this is expensive when it returns false; use this function
// when you expect it to return true in the common case.
return x != null && Object(x) === x;
},
ToObject: function(o, optMessage) {
return Object(ES.CheckObjectCoercible(o, optMessage));
},
IsCallable: function(x) {
return typeof x === 'function' &&
// some versions of IE say that typeof /abc/ === 'function'
_toString.call(x) === '[object Function]';
},
ToInt32: function(x) {
return x >> 0;
},
ToUint32: function(x) {
return x >>> 0;
},
ToInteger: function(value) {
var number = +value;
if (Number.isNaN(number)) return 0;
if (number === 0 || !Number.isFinite(number)) return number;
return Math.sign(number) * Math.floor(Math.abs(number));
},
ToLength: function(value) {
var len = ES.ToInteger(value);
if (len <= 0) return 0; // includes converting -0 to +0
if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER;
return len;
},
SameValue: function(a, b) {
if (a === b) {
// 0 === -0, but they are not identical.
if (a === 0) return 1 / a === 1 / b;
return true;
}
return Number.isNaN(a) && Number.isNaN(b);
},
SameValueZero: function(a, b) {
// same as SameValue except for SameValueZero(+0, -0) == true
return (a === b) || (Number.isNaN(a) && Number.isNaN(b));
},
IsIterable: function(o) {
return ES.TypeIsObject(o) &&
(o[$iterator$] !== undefined || isArguments(o));
},
GetIterator: function(o) {
if (isArguments(o)) {
// special case support for `arguments`
return new ArrayIterator(o, "value");
}
var it = o[$iterator$]();
if (!ES.TypeIsObject(it)) {
throw new TypeError('bad iterator');
}
return it;
},
IteratorNext: function(it) {
var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next();
if (!ES.TypeIsObject(result)) {
throw new TypeError('bad iterator');
}
return result;
},
Construct: function(C, args) {
// CreateFromConstructor
var obj;
if (ES.IsCallable(C['@@create'])) {
obj = C['@@create']();
} else {
// OrdinaryCreateFromConstructor
obj = create(C.prototype || null);
}
// Mark that we've used the es6 construct path
// (see emulateES6construct)
defineProperties(obj, { _es6construct: true });
// Call the constructor.
var result = C.apply(obj, args);
return ES.TypeIsObject(result) ? result : obj;
}
};
var numberConversion = (function () {
// from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266
// with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200
function roundToEven(n) {
var w = Math.floor(n), f = n - w;
if (f < 0.5) {
return w;
}
if (f > 0.5) {
return w + 1;
}
return w % 2 ? w + 1 : w;
}
function packIEEE754(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1,
s, e, f, ln,
i, bits, str, bytes;
// Compute sign, exponent, fraction
if (v !== v) {
// NaN
// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
e = (1 << ebits) - 1;
f = Math.pow(2, fbits - 1);
s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1;
f = 0;
s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0;
f = 0;
s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = Math.abs(v);
if (v >= Math.pow(2, 1 - bias)) {
e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023);
f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits));
if (f / Math.pow(2, fbits) >= 2) {
e = e + 1;
f = 1;
}
if (e > bias) {
// Overflow
e = (1 << ebits) - 1;
f = 0;
} else {
// Normal
e = e + bias;
f = f - Math.pow(2, fbits);
}
} else {
// Subnormal
e = 0;
f = roundToEven(v / Math.pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
bits = [];
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = Math.floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = Math.floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
// Bits to bytes
bytes = [];
while (str.length) {
bytes.push(parseInt(str.slice(0, 8), 2));
str = str.slice(8);
}
return bytes;
}
function unpackIEEE754(bytes, ebits, fbits) {
// Bytes to bits
var bits = [], i, j, b, str,
bias, s, e, f;
for (i = bytes.length; i; i -= 1) {
b = bytes[i - 1];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0);
b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
// Unpack sign, exponent, fraction
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.slice(0, 1), 2) ? -1 : 1;
e = parseInt(str.slice(1, 1 + ebits), 2);
f = parseInt(str.slice(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
// Normalized
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
} else if (f !== 0) {
// Denormalized
return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
}
function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); }
function packFloat64(v) { return packIEEE754(v, 11, 52); }
function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); }
function packFloat32(v) { return packIEEE754(v, 8, 23); }
var conversions = {
toFloat32: function (num) { return unpackFloat32(packFloat32(num)); }
};
if (typeof Float32Array !== 'undefined') {
var float32array = new Float32Array(1);
conversions.toFloat32 = function (num) {
float32array[0] = num;
return float32array[0];
};
}
return conversions;
}());
defineProperties(String, {
fromCodePoint: function(_) { // length = 1
var points = _slice.call(arguments, 0, arguments.length);
var result = [];
var next;
for (var i = 0, length = points.length; i < length; i++) {
next = Number(points[i]);
if (!ES.SameValue(next, ES.ToInteger(next)) ||
next < 0 || next > 0x10FFFF) {
throw new RangeError('Invalid code point ' + next);
}
if (next < 0x10000) {
result.push(String.fromCharCode(next));
} else {
next -= 0x10000;
result.push(String.fromCharCode((next >> 10) + 0xD800));
result.push(String.fromCharCode((next % 0x400) + 0xDC00));
}
}
return result.join('');
},
raw: function(callSite) { // raw.length===1
var substitutions = _slice.call(arguments, 1, arguments.length);
var cooked = ES.ToObject(callSite, 'bad callSite');
var rawValue = cooked.raw;
var raw = ES.ToObject(rawValue, 'bad raw value');
var len = Object.keys(raw).length;
var literalsegments = ES.ToLength(len);
if (literalsegments === 0) {
return '';
}
var stringElements = [];
var nextIndex = 0;
var nextKey, next, nextSeg, nextSub;
while (nextIndex < literalsegments) {
nextKey = String(nextIndex);
next = raw[nextKey];
nextSeg = String(next);
stringElements.push(nextSeg);
if (nextIndex + 1 >= literalsegments) {
break;
}
next = substitutions[nextKey];
if (next === undefined) {
break;
}
nextSub = String(next);
stringElements.push(nextSub);
nextIndex++;
}
return stringElements.join('');
}
});
var StringShims = {
// Fast repeat, uses the `Exponentiation by squaring` algorithm.
// Perf: http://jsperf.com/string-repeat2/2
repeat: (function() {
var repeat = function(s, times) {
if (times < 1) return '';
if (times % 2) return repeat(s, times - 1) + s;
var half = repeat(s, times / 2);
return half + half;
};
return function(times) {
var thisStr = String(ES.CheckObjectCoercible(this));
times = ES.ToInteger(times);
if (times < 0 || times === Infinity) {
throw new RangeError('Invalid String#repeat value');
}
return repeat(thisStr, times);
};
})(),
startsWith: function(searchStr) {
var thisStr = String(ES.CheckObjectCoercible(this));
if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex');
searchStr = String(searchStr);
var startArg = arguments.length > 1 ? arguments[1] : undefined;
var start = Math.max(ES.ToInteger(startArg), 0);
return thisStr.slice(start, start + searchStr.length) === searchStr;
},
endsWith: function(searchStr) {
var thisStr = String(ES.CheckObjectCoercible(this));
if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex');
searchStr = String(searchStr);
var thisLen = thisStr.length;
var posArg = arguments.length > 1 ? arguments[1] : undefined;
var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg);
var end = Math.min(Math.max(pos, 0), thisLen);
return thisStr.slice(end - searchStr.length, end) === searchStr;
},
contains: function(searchString) {
var position = arguments.length > 1 ? arguments[1] : undefined;
// Somehow this trick makes method 100% compat with the spec.
return _indexOf.call(this, searchString, position) !== -1;
},
codePointAt: function(pos) {
var thisStr = String(ES.CheckObjectCoercible(this));
var position = ES.ToInteger(pos);
var length = thisStr.length;
if (position < 0 || position >= length) return undefined;
var first = thisStr.charCodeAt(position);
var isEnd = (position + 1 === length);
if (first < 0xD800 || first > 0xDBFF || isEnd) return first;
var second = thisStr.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) return first;
return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000;
}
};
defineProperties(String.prototype, StringShims);
var hasStringTrimBug = '\u0085'.trim().length !== 1;
if (hasStringTrimBug) {
var originalStringTrim = String.prototype.trim;
delete String.prototype.trim;
// whitespace from: http://es5.github.io/#x15.5.4.20
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
var ws = [
'\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
'\u2029\uFEFF'
].join('');
var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*');
var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$');
defineProperties(String.prototype, {
trim: function() {
if (this === undefined || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
}
});
}
// see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator
var StringIterator = function(s) {
this._s = String(ES.CheckObjectCoercible(s));
this._i = 0;
};
StringIterator.prototype.next = function() {
var s = this._s, i = this._i;
if (s === undefined || i >= s.length) {
this._s = undefined;
return { value: undefined, done: true };
}
var first = s.charCodeAt(i), second, len;
if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) {
len = 1;
} else {
second = s.charCodeAt(i+1);
len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2;
}
this._i = i + len;
return { value: s.substr(i, len), done: false };
};
addIterator(StringIterator.prototype);
addIterator(String.prototype, function() {
return new StringIterator(this);
});
if (!startsWithIsCompliant) {
// Firefox has a noncompliant startsWith implementation
String.prototype.startsWith = StringShims.startsWith;
String.prototype.endsWith = StringShims.endsWith;
}
defineProperties(Array, {
from: function(iterable) {
var mapFn = arguments.length > 1 ? arguments[1] : undefined;
var thisArg = arguments.length > 2 ? arguments[2] : undefined;
var list = ES.ToObject(iterable, 'bad iterable');
if (mapFn !== undefined && !ES.IsCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
var usingIterator = ES.IsIterable(list);
// does the spec really mean that Arrays should use ArrayIterator?
// https://bugs.ecmascript.org/show_bug.cgi?id=2416
//if (Array.isArray(list)) { usingIterator=false; }
var length = usingIterator ? 0 : ES.ToLength(list.length);
var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length);
var it = usingIterator ? ES.GetIterator(list) : null;
var value;
for (var i = 0; usingIterator || (i < length); i++) {
if (usingIterator) {
value = ES.IteratorNext(it);
if (value.done) {
length = i;
break;
}
value = value.value;
} else {
value = list[i];
}
if (mapFn) {
result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i);
} else {
result[i] = value;
}
}
result.length = length;
return result;
},
of: function() {
return Array.from(arguments);
}
});
// Our ArrayIterator is private; see
// https://github.com/paulmillr/es6-shim/issues/252
ArrayIterator = function(array, kind) {
this.i = 0;
this.array = array;
this.kind = kind;
};
defineProperties(ArrayIterator.prototype, {
next: function() {
var i = this.i, array = this.array;
if (i === undefined || this.kind === undefined) {
throw new TypeError('Not an ArrayIterator');
}
if (array!==undefined) {
var len = ES.ToLength(array.length);
for (; i < len; i++) {
var kind = this.kind;
var retval;
if (kind === "key") {
retval = i;
} else if (kind === "value") {
retval = array[i];
} else if (kind === "entry") {
retval = [i, array[i]];
}
this.i = i + 1;
return { value: retval, done: false };
}
}
this.array = undefined;
return { value: undefined, done: true };
}
});
addIterator(ArrayIterator.prototype);
defineProperties(Array.prototype, {
copyWithin: function(target, start) {
var end = arguments[2]; // copyWithin.length must be 2
var o = ES.ToObject(this);
var len = ES.ToLength(o.length);
target = ES.ToInteger(target);
start = ES.ToInteger(start);
var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);
var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
end = (end===undefined) ? len : ES.ToInteger(end);
var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
var count = Math.min(fin - from, len - to);
var direction = 1;
if (from < to && to < (from + count)) {
direction = -1;
from += count - 1;
to += count - 1;
}
while (count > 0) {
if (_hasOwnProperty.call(o, from)) {
o[to] = o[from];
} else {
delete o[from];
}
from += direction;
to += direction;
count -= 1;
}
return o;
},
fill: function(value) {
var start = arguments.length > 1 ? arguments[1] : undefined;
var end = arguments.length > 2 ? arguments[2] : undefined;
var O = ES.ToObject(this);
var len = ES.ToLength(O.length);
start = ES.ToInteger(start === undefined ? 0 : start);
end = ES.ToInteger(end === undefined ? len : end);
var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
var relativeEnd = end < 0 ? len + end : end;
for (var i = relativeStart; i < len && i < relativeEnd; ++i) {
O[i] = value;
}
return O;
},
find: function(predicate) {
var list = ES.ToObject(this);
var length = ES.ToLength(list.length);
if (!ES.IsCallable(predicate)) {
throw new TypeError('Array#find: predicate must be a function');
}
var thisArg = arguments[1];
for (var i = 0, value; i < length; i++) {
if (i in list) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) return value;
}
}
return undefined;
},
findIndex: function(predicate) {
var list = ES.ToObject(this);
var length = ES.ToLength(list.length);
if (!ES.IsCallable(predicate)) {
throw new TypeError('Array#findIndex: predicate must be a function');
}
var thisArg = arguments[1];
for (var i = 0; i < length; i++) {
if (i in list) {
if (predicate.call(thisArg, list[i], i, list)) return i;
}
}
return -1;
},
keys: function() {
return new ArrayIterator(this, "key");
},
values: function() {
return new ArrayIterator(this, "value");
},
entries: function() {
return new ArrayIterator(this, "entry");
}
});
addIterator(Array.prototype, function() { return this.values(); });
// Chrome defines keys/values/entries on Array, but doesn't give us
// any way to identify its iterator. So add our own shimmed field.
if (Object.getPrototypeOf) {
addIterator(Object.getPrototypeOf([].values()));
}
var maxSafeInteger = Math.pow(2, 53) - 1;
defineProperties(Number, {
MAX_SAFE_INTEGER: maxSafeInteger,
MIN_SAFE_INTEGER: -maxSafeInteger,
EPSILON: 2.220446049250313e-16,
parseInt: globals.parseInt,
parseFloat: globals.parseFloat,
isFinite: function(value) {
return typeof value === 'number' && global_isFinite(value);
},
isInteger: function(value) {
return Number.isFinite(value) &&
ES.ToInteger(value) === value;
},
isSafeInteger: function(value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
},
isNaN: function(value) {
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN('foo') => true
return value !== value;
}
});
if (supportsDescriptors) {
defineProperties(Object, {
getPropertyDescriptor: function(subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (pd === undefined && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
},
getPropertyNames: function(subject) {
var result = Object.getOwnPropertyNames(subject);
var proto = Object.getPrototypeOf(subject);
var addProperty = function(property) {
if (result.indexOf(property) === -1) {
result.push(property);
}
};
while (proto !== null) {
Object.getOwnPropertyNames(proto).forEach(addProperty);
proto = Object.getPrototypeOf(proto);
}
return result;
}
});
defineProperties(Object, {
// 19.1.3.1
assign: function(target, source) {
if (!ES.TypeIsObject(target)) {
throw new TypeError('target must be an object');
}
return Array.prototype.reduce.call(arguments, function(target, source) {
return Object.keys(Object(source)).reduce(function(target, key) {
target[key] = source[key];
return target;
}, target);
});
},
is: function(a, b) {
return ES.SameValue(a, b);
},
// 19.1.3.9
// shim from https://gist.github.com/WebReflection/5593554
setPrototypeOf: (function(Object, magic) {
var set;
var checkArgs = function(O, proto) {
if (!ES.TypeIsObject(O)) {
throw new TypeError('cannot set prototype on a non-object');
}
if (!(proto===null || ES.TypeIsObject(proto))) {
throw new TypeError('can only set prototype to an object or null'+proto);
}
};
var setPrototypeOf = function(O, proto) {
checkArgs(O, proto);
set.call(O, proto);
return O;
};
try {
// this works already in Firefox and Safari
set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set;
set.call({}, null);
} catch (e) {
if (Object.prototype !== {}[magic]) {
// IE < 11 cannot be shimmed
return;
}
// probably Chrome or some old Mobile stock browser
set = function(proto) {
this[magic] = proto;
};
// please note that this will **not** work
// in those browsers that do not inherit
// __proto__ by mistake from Object.prototype
// in these cases we should probably throw an error
// or at least be informed about the issue
setPrototypeOf.polyfill = setPrototypeOf(
setPrototypeOf({}, null),
Object.prototype
) instanceof Object;
// setPrototypeOf.polyfill === true means it works as meant
// setPrototypeOf.polyfill === false means it's not 100% reliable
// setPrototypeOf.polyfill === undefined
// or
// setPrototypeOf.polyfill == null means it's not a polyfill
// which means it works as expected
// we can even delete Object.prototype.__proto__;
}
return setPrototypeOf;
})(Object, '__proto__')
});
}
// Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work,
// but Object.create(null) does.
if (Object.setPrototypeOf && Object.getPrototypeOf &&
Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null &&
Object.getPrototypeOf(Object.create(null)) === null) {
(function() {
var FAKENULL = Object.create(null);
var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf;
Object.getPrototypeOf = function(o) {
var result = gpo(o);
return result === FAKENULL ? null : result;
};
Object.setPrototypeOf = function(o, p) {
if (p === null) { p = FAKENULL; }
return spo(o, p);
};
Object.setPrototypeOf.polyfill = false;
})();
}
try {
Object.keys('foo');
} catch (e) {
var originalObjectKeys = Object.keys;
Object.keys = function (obj) {
return originalObjectKeys(ES.ToObject(obj));
};
}
var MathShims = {
acosh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value < 1) return NaN;
if (value === 1) return 0;
if (value === Infinity) return value;
return Math.log(value + Math.sqrt(value * value - 1));
},
asinh: function(value) {
value = Number(value);
if (value === 0 || !global_isFinite(value)) {
return value;
}
return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1));
},
atanh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value < -1 || value > 1) {
return NaN;
}
if (value === -1) return -Infinity;
if (value === 1) return Infinity;
if (value === 0) return value;
return 0.5 * Math.log((1 + value) / (1 - value));
},
cbrt: function(value) {
value = Number(value);
if (value === 0) return value;
var negate = value < 0, result;
if (negate) value = -value;
result = Math.pow(value, 1/3);
return negate ? -result : result;
},
clz32: function(value) {
// See https://bugs.ecmascript.org/show_bug.cgi?id=2465
value = Number(value);
var number = ES.ToUint32(value);
if (number === 0) {
return 32;
}
return 32 - (number).toString(2).length;
},
cosh: function(value) {
value = Number(value);
if (value === 0) return 1; // +0 or -0
if (Number.isNaN(value)) return NaN;
if (!global_isFinite(value)) return Infinity;
if (value < 0) value = -value;
if (value > 21) return Math.exp(value) / 2;
return (Math.exp(value) + Math.exp(-value)) / 2;
},
expm1: function(value) {
value = Number(value);
if (value === -Infinity) return -1;
if (!global_isFinite(value) || value === 0) return value;
return Math.exp(value) - 1;
},
hypot: function(x, y) {
var anyNaN = false;
var allZero = true;
var anyInfinity = false;
var numbers = [];
Array.prototype.every.call(arguments, function(arg) {
var num = Number(arg);
if (Number.isNaN(num)) anyNaN = true;
else if (num === Infinity || num === -Infinity) anyInfinity = true;
else if (num !== 0) allZero = false;
if (anyInfinity) {
return false;
} else if (!anyNaN) {
numbers.push(Math.abs(num));
}
return true;
});
if (anyInfinity) return Infinity;
if (anyNaN) return NaN;
if (allZero) return 0;
numbers.sort(function (a, b) { return b - a; });
var largest = numbers[0];
var divided = numbers.map(function (number) { return number / largest; });
var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0);
return largest * Math.sqrt(sum);
},
log2: function(value) {
return Math.log(value) * Math.LOG2E;
},
log10: function(value) {
return Math.log(value) * Math.LOG10E;
},
log1p: function(value) {
value = Number(value);
if (value < -1 || Number.isNaN(value)) return NaN;
if (value === 0 || value === Infinity) return value;
if (value === -1) return -Infinity;
var result = 0;
var n = 50;
if (value < 0 || value > 1) return Math.log(1 + value);
for (var i = 1; i < n; i++) {
if ((i % 2) === 0) {
result -= Math.pow(value, i) / i;
} else {
result += Math.pow(value, i) / i;
}
}
return result;
},
sign: function(value) {
var number = +value;
if (number === 0) return number;
if (Number.isNaN(number)) return number;
return number < 0 ? -1 : 1;
},
sinh: function(value) {
value = Number(value);
if (!global_isFinite(value) || value === 0) return value;
return (Math.exp(value) - Math.exp(-value)) / 2;
},
tanh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value === 0) return value;
if (value === Infinity) return 1;
if (value === -Infinity) return -1;
return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value));
},
trunc: function(value) {
var number = Number(value);
return number < 0 ? -Math.floor(-number) : Math.floor(number);
},
imul: function(x, y) {
// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
x = ES.ToUint32(x);
y = ES.ToUint32(y);
var ah = (x >>> 16) & 0xffff;
var al = x & 0xffff;
var bh = (y >>> 16) & 0xffff;
var bl = y & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
},
fround: function(x) {
if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) {
return x;
}
var num = Number(x);
return numberConversion.toFloat32(num);
}
};
defineProperties(Math, MathShims);
if (Math.imul(0xffffffff, 5) !== -5) {
// Safari 6.1, at least, reports "0" for this value
Math.imul = MathShims.imul;
}
// Promises
// Simplest possible implementation; use a 3rd-party library if you
// want the best possible speed and/or long stack traces.
var PromiseShim = (function() {
var Promise, Promise$prototype;
ES.IsPromise = function(promise) {
if (!ES.TypeIsObject(promise)) {
return false;
}
if (!promise._promiseConstructor) {
// _promiseConstructor is a bit more unique than _status, so we'll
// check that instead of the [[PromiseStatus]] internal field.
return false;
}
if (promise._status === undefined) {
return false; // uninitialized
}
return true;
};
// "PromiseCapability" in the spec is what most promise implementations
// call a "deferred".
var PromiseCapability = function(C) {
if (!ES.IsCallable(C)) {
throw new TypeError('bad promise constructor');
}
var capability = this;
var resolver = function(resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
};
capability.promise = ES.Construct(C, [resolver]);
// see https://bugs.ecmascript.org/show_bug.cgi?id=2478
if (!capability.promise._es6construct) {
throw new TypeError('bad promise constructor');
}
if (!(ES.IsCallable(capability.resolve) &&
ES.IsCallable(capability.reject))) {
throw new TypeError('bad promise constructor');
}
};
// find an appropriate setImmediate-alike
var setTimeout = globals.setTimeout;
var makeZeroTimeout;
if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) {
makeZeroTimeout = function() {
// from http://dbaron.org/log/20100309-faster-timeouts
var timeouts = [];
var messageName = "zero-timeout-message";
var setZeroTimeout = function(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
};
var handleMessage = function(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length === 0) { return; }
var fn = timeouts.shift();
fn();
}
};
window.addEventListener("message", handleMessage, true);
return setZeroTimeout;
};
}
var makePromiseAsap = function() {
// An efficient task-scheduler based on a pre-existing Promise
// implementation, which we can use even if we override the
// global Promise below (in order to workaround bugs)
// https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671
var P = globals.Promise;
return P && P.resolve && function(task) {
return P.resolve().then(task);
};
};
var enqueue = ES.IsCallable(globals.setImmediate) ?
globals.setImmediate.bind(globals) :
typeof process === 'object' && process.nextTick ? process.nextTick :
makePromiseAsap() ||
(ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() :
function(task) { setTimeout(task, 0); }); // fallback
var triggerPromiseReactions = function(reactions, x) {
reactions.forEach(function(reaction) {
enqueue(function() {
// PromiseReactionTask
var handler = reaction.handler;
var capability = reaction.capability;
var resolve = capability.resolve;
var reject = capability.reject;
try {
var result = handler(x);
if (result === capability.promise) {
throw new TypeError('self resolution');
}
var updateResult =
updatePromiseFromPotentialThenable(result, capability);
if (!updateResult) {
resolve(result);
}
} catch (e) {
reject(e);
}
});
});
};
var updatePromiseFromPotentialThenable = function(x, capability) {
if (!ES.TypeIsObject(x)) {
return false;
}
var resolve = capability.resolve;
var reject = capability.reject;
try {
var then = x.then; // only one invocation of accessor
if (!ES.IsCallable(then)) { return false; }
then.call(x, resolve, reject);
} catch(e) {
reject(e);
}
return true;
};
var promiseResolutionHandler = function(promise, onFulfilled, onRejected){
return function(x) {
if (x === promise) {
return onRejected(new TypeError('self resolution'));
}
var C = promise._promiseConstructor;
var capability = new PromiseCapability(C);
var updateResult = updatePromiseFromPotentialThenable(x, capability);
if (updateResult) {
return capability.promise.then(onFulfilled, onRejected);
} else {
return onFulfilled(x);
}
};
};
Promise = function(resolver) {
var promise = this;
promise = emulateES6construct(promise);
if (!promise._promiseConstructor) {
// we use _promiseConstructor as a stand-in for the internal
// [[PromiseStatus]] field; it's a little more unique.
throw new TypeError('bad promise');
}
if (promise._status !== undefined) {
throw new TypeError('promise already initialized');
}
// see https://bugs.ecmascript.org/show_bug.cgi?id=2482
if (!ES.IsCallable(resolver)) {
throw new TypeError('not a valid resolver');
}
promise._status = 'unresolved';
promise._resolveReactions = [];
promise._rejectReactions = [];
var resolve = function(resolution) {
if (promise._status !== 'unresolved') { return; }
var reactions = promise._resolveReactions;
promise._result = resolution;
promise._resolveReactions = undefined;
promise._rejectReactions = undefined;
promise._status = 'has-resolution';
triggerPromiseReactions(reactions, resolution);
};
var reject = function(reason) {
if (promise._status !== 'unresolved') { return; }
var reactions = promise._rejectReactions;
promise._result = reason;
promise._resolveReactions = undefined;
promise._rejectReactions = undefined;
promise._status = 'has-rejection';
triggerPromiseReactions(reactions, reason);
};
try {
resolver(resolve, reject);
} catch (e) {
reject(e);
}
return promise;
};
Promise$prototype = Promise.prototype;
defineProperties(Promise, {
'@@create': function(obj) {
var constructor = this;
// AllocatePromise
// The `obj` parameter is a hack we use for es5
// compatibility.
var prototype = constructor.prototype || Promise$prototype;
obj = obj || create(prototype);
defineProperties(obj, {
_status: undefined,
_result: undefined,
_resolveReactions: undefined,
_rejectReactions: undefined,
_promiseConstructor: undefined
});
obj._promiseConstructor = constructor;
return obj;
}
});
var _promiseAllResolver = function(index, values, capability, remaining) {
var done = false;
return function(x) {
if (done) { return; } // protect against being called multiple times
done = true;
values[index] = x;
if ((--remaining.count) === 0) {
var resolve = capability.resolve;
resolve(values); // call w/ this===undefined
}
};
};
Promise.all = function(iterable) {
var C = this;
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
try {
if (!ES.IsIterable(iterable)) {
throw new TypeError('bad iterable');
}
var it = ES.GetIterator(iterable);
var values = [], remaining = { count: 1 };
for (var index = 0; ; index++) {
var next = ES.IteratorNext(it);
if (next.done) {
break;
}
var nextPromise = C.resolve(next.value);
var resolveElement = _promiseAllResolver(
index, values, capability, remaining
);
remaining.count++;
nextPromise.then(resolveElement, capability.reject);
}
if ((--remaining.count) === 0) {
resolve(values); // call w/ this===undefined
}
} catch (e) {
reject(e);
}
return capability.promise;
};
Promise.race = function(iterable) {
var C = this;
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
try {
if (!ES.IsIterable(iterable)) {
throw new TypeError('bad iterable');
}
var it = ES.GetIterator(iterable);
while (true) {
var next = ES.IteratorNext(it);
if (next.done) {
// If iterable has no items, resulting promise will never
// resolve; see:
// https://github.com/domenic/promises-unwrapping/issues/75
// https://bugs.ecmascript.org/show_bug.cgi?id=2515
break;
}
var nextPromise = C.resolve(next.value);
nextPromise.then(resolve, reject);
}
} catch (e) {
reject(e);
}
return capability.promise;
};
Promise.reject = function(reason) {
var C = this;
var capability = new PromiseCapability(C);
var reject = capability.reject;
reject(reason); // call with this===undefined
return capability.promise;
};
Promise.resolve = function(v) {
var C = this;
if (ES.IsPromise(v)) {
var constructor = v._promiseConstructor;
if (constructor === C) { return v; }
}
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
resolve(v); // call with this===undefined
return capability.promise;
};
Promise.prototype['catch'] = function( onRejected ) {
return this.then(undefined, onRejected);
};
Promise.prototype.then = function( onFulfilled, onRejected ) {
var promise = this;
if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); }
// this.constructor not this._promiseConstructor; see
// https://bugs.ecmascript.org/show_bug.cgi?id=2513
var C = this.constructor;
var capability = new PromiseCapability(C);
if (!ES.IsCallable(onRejected)) {
onRejected = function(e) { throw e; };
}
if (!ES.IsCallable(onFulfilled)) {
onFulfilled = function(x) { return x; };
}
var resolutionHandler =
promiseResolutionHandler(promise, onFulfilled, onRejected);
var resolveReaction =
{ capability: capability, handler: resolutionHandler };
var rejectReaction =
{ capability: capability, handler: onRejected };
switch (promise._status) {
case 'unresolved':
promise._resolveReactions.push(resolveReaction);
promise._rejectReactions.push(rejectReaction);
break;
case 'has-resolution':
triggerPromiseReactions([resolveReaction], promise._result);
break;
case 'has-rejection':
triggerPromiseReactions([rejectReaction], promise._result);
break;
default:
throw new TypeError('unexpected');
}
return capability.promise;
};
return Promise;
})();
// export the Promise constructor.
defineProperties(globals, { Promise: PromiseShim });
// In Chrome 33 (and thereabouts) Promise is defined, but the
// implementation is buggy in a number of ways. Let's check subclassing
// support to see if we have a buggy implementation.
var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) {
return S.resolve(42) instanceof S;
});
var promiseIgnoresNonFunctionThenCallbacks = (function () {
try {
globals.Promise.reject(42).then(null, 5).then(null, function () {});
return true;
} catch (ex) {
return false;
}
}());
if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) {
globals.Promise = PromiseShim;
}
// Map and Set require a true ES5 environment
if (supportsDescriptors) {
var fastkey = function fastkey(key) {
var type = typeof key;
if (type === 'string') {
return '$' + key;
} else if (type === 'number') {
// note that -0 will get coerced to "0" when used as a property key
return key;
}
return null;
};
var emptyObject = function emptyObject() {
// accomodate some older not-quite-ES5 browsers
return Object.create ? Object.create(null) : {};
};
var collectionShims = {
Map: (function() {
var empty = {};
function MapEntry(key, value) {
this.key = key;
this.value = value;
this.next = null;
this.prev = null;
}
MapEntry.prototype.isRemoved = function() {
return this.key === empty;
};
function MapIterator(map, kind) {
this.head = map._head;
this.i = this.head;
this.kind = kind;
}
MapIterator.prototype = {
next: function() {
var i = this.i, kind = this.kind, head = this.head, result;
if (this.i === undefined) {
return { value: undefined, done: true };
}
while (i.isRemoved() && i !== head) {
// back up off of removed entries
i = i.prev;
}
// advance to next unreturned element.
while (i.next !== head) {
i = i.next;
if (!i.isRemoved()) {
if (kind === "key") {
result = i.key;
} else if (kind === "value") {
result = i.value;
} else {
result = [i.key, i.value];
}
this.i = i;
return { value: result, done: false };
}
}
// once the iterator is done, it is done forever.
this.i = undefined;
return { value: undefined, done: true };
}
};
addIterator(MapIterator.prototype);
function Map(iterable) {
var map = this;
map = emulateES6construct(map);
if (!map._es6map) {
throw new TypeError('bad map');
}
var head = new MapEntry(null, null);
// circular doubly-linked list.
head.next = head.prev = head;
defineProperties(map, {
'_head': head,
'_storage': emptyObject(),
'_size': 0
});
// Optionally initialize map from iterable
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = map.set;
if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
if (!ES.TypeIsObject(nextItem)) {
throw new TypeError('expected iterable of pairs');
}
adder.call(map, nextItem[0], nextItem[1]);
}
}
return map;
}
var Map$prototype = Map.prototype;
defineProperties(Map, {
'@@create': function(obj) {
var constructor = this;
var prototype = constructor.prototype || Map$prototype;
obj = obj || create(prototype);
defineProperties(obj, { _es6map: true });
return obj;
}
});
Object.defineProperty(Map.prototype, 'size', {
configurable: true,
enumerable: false,
get: function() {
if (typeof this._size === 'undefined') {
throw new TypeError('size method called on incompatible Map');
}
return this._size;
}
});
defineProperties(Map.prototype, {
get: function(key) {
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
var entry = this._storage[fkey];
return entry ? entry.value : undefined;
}
var head = this._head, i = head;
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
return i.value;
}
}
return undefined;
},
has: function(key) {
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
return typeof this._storage[fkey] !== 'undefined';
}
var head = this._head, i = head;
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
return true;
}
}
return false;
},
set: function(key, value) {
var head = this._head, i = head, entry;
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
if (typeof this._storage[fkey] !== 'undefined') {
this._storage[fkey].value = value;
return;
} else {
entry = this._storage[fkey] = new MapEntry(key, value);
i = head.prev;
// fall through
}
}
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
i.value = value;
return;
}
}
entry = entry || new MapEntry(key, value);
if (ES.SameValue(-0, key)) {
entry.key = +0; // coerce -0 to +0 in entry
}
entry.next = this._head;
entry.prev = this._head.prev;
entry.prev.next = entry;
entry.next.prev = entry;
this._size += 1;
},
'delete': function(key) {
var head = this._head, i = head;
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
if (typeof this._storage[fkey] === 'undefined') {
return false;
}
i = this._storage[fkey].prev;
delete this._storage[fkey];
// fall through
}
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
i.key = i.value = empty;
i.prev.next = i.next;
i.next.prev = i.prev;
this._size -= 1;
return true;
}
}
return false;
},
clear: function() {
this._size = 0;
this._storage = emptyObject();
var head = this._head, i = head, p = i.next;
while ((i = p) !== head) {
i.key = i.value = empty;
p = i.next;
i.next = i.prev = head;
}
head.next = head.prev = head;
},
keys: function() {
return new MapIterator(this, "key");
},
values: function() {
return new MapIterator(this, "value");
},
entries: function() {
return new MapIterator(this, "key+value");
},
forEach: function(callback) {
var context = arguments.length > 1 ? arguments[1] : null;
var it = this.entries();
for (var entry = it.next(); !entry.done; entry = it.next()) {
callback.call(context, entry.value[1], entry.value[0], this);
}
}
});
addIterator(Map.prototype, function() { return this.entries(); });
return Map;
})(),
Set: (function() {
// Creating a Map is expensive. To speed up the common case of
// Sets containing only string or numeric keys, we use an object
// as backing storage and lazily create a full Map only when
// required.
var SetShim = function Set(iterable) {
var set = this;
set = emulateES6construct(set);
if (!set._es6set) {
throw new TypeError('bad set');
}
defineProperties(set, {
'[[SetData]]': null,
'_storage': emptyObject()
});
// Optionally initialize map from iterable
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = set.add;
if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
adder.call(set, nextItem);
}
}
return set;
};
var Set$prototype = SetShim.prototype;
defineProperties(SetShim, {
'@@create': function(obj) {
var constructor = this;
var prototype = constructor.prototype || Set$prototype;
obj = obj || create(prototype);
defineProperties(obj, { _es6set: true });
return obj;
}
});
// Switch from the object backing storage to a full Map.
var ensureMap = function ensureMap(set) {
if (!set['[[SetData]]']) {
var m = set['[[SetData]]'] = new collectionShims.Map();
Object.keys(set._storage).forEach(function(k) {
// fast check for leading '$'
if (k.charCodeAt(0) === 36) {
k = k.slice(1);
} else {
k = +k;
}
m.set(k, k);
});
set._storage = null; // free old backing storage
}
};
Object.defineProperty(SetShim.prototype, 'size', {
configurable: true,
enumerable: false,
get: function() {
if (typeof this._storage === 'undefined') {
// https://github.com/paulmillr/es6-shim/issues/176
throw new TypeError('size method called on incompatible Set');
}
ensureMap(this);
return this['[[SetData]]'].size;
}
});
defineProperties(SetShim.prototype, {
has: function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
return !!this._storage[fkey];
}
ensureMap(this);
return this['[[SetData]]'].has(key);
},
add: function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
this._storage[fkey]=true;
return;
}
ensureMap(this);
return this['[[SetData]]'].set(key, key);
},
'delete': function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
delete this._storage[fkey];
return;
}
ensureMap(this);
return this['[[SetData]]']['delete'](key);
},
clear: function() {
if (this._storage) {
this._storage = emptyObject();
return;
}
return this['[[SetData]]'].clear();
},
keys: function() {
ensureMap(this);
return this['[[SetData]]'].keys();
},
values: function() {
ensureMap(this);
return this['[[SetData]]'].values();
},
entries: function() {
ensureMap(this);
return this['[[SetData]]'].entries();
},
forEach: function(callback) {
var context = arguments.length > 1 ? arguments[1] : null;
var entireSet = this;
ensureMap(this);
this['[[SetData]]'].forEach(function(value, key) {
callback.call(context, key, key, entireSet);
});
}
});
addIterator(SetShim.prototype, function() { return this.values(); });
return SetShim;
})()
};
defineProperties(globals, collectionShims);
if (globals.Map || globals.Set) {
/*
- In Firefox < 23, Map#size is a function.
- In all current Firefox, Set#entries/keys/values & Map#clear do not exist
- https://bugzilla.mozilla.org/show_bug.cgi?id=869996
- In Firefox 24, Map and Set do not implement forEach
- In Firefox 25 at least, Map and Set are callable without "new"
*/
if (
typeof globals.Map.prototype.clear !== 'function' ||
new globals.Set().size !== 0 ||
new globals.Map().size !== 0 ||
typeof globals.Map.prototype.keys !== 'function' ||
typeof globals.Set.prototype.keys !== 'function' ||
typeof globals.Map.prototype.forEach !== 'function' ||
typeof globals.Set.prototype.forEach !== 'function' ||
isCallableWithoutNew(globals.Map) ||
isCallableWithoutNew(globals.Set) ||
!supportsSubclassing(globals.Map, function(M) {
return (new M([])) instanceof M;
})
) {
globals.Map = collectionShims.Map;
globals.Set = collectionShims.Set;
}
}
// Shim incomplete iterator implementations.
addIterator(Object.getPrototypeOf((new globals.Map()).keys()));
addIterator(Object.getPrototypeOf((new globals.Set()).keys()));
}
};
main(); // CommonJS and <script>
});
|
packages/material-ui-icons/src/WatchLaterSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><defs><path id="a" d="M0 0h24v24H0z" /></defs><g><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z" /></g></React.Fragment>
, 'WatchLaterSharp');
|
addons/knobs/src/components/GroupTabs.js | rhalff/storybook | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { baseFonts } from '@storybook/components';
const styles = {
empty: {
flex: 1,
display: 'flex',
...baseFonts,
fontSize: 11,
letterSpacing: '1px',
textTransform: 'uppercase',
alignItems: 'center',
justifyContent: 'center',
},
wrapper: {
flex: '1 1 auto',
display: 'flex',
flexDirection: 'column',
background: 'white',
borderRadius: 4,
border: 'solid 1px rgb(236, 236, 236)',
width: '100%',
},
tabbar: {
display: 'flex',
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
borderBottom: 'solid 1px #eaeaea',
},
content: {
flex: '1 1 0',
display: 'flex',
overflow: 'auto',
},
tablink: {
...baseFonts,
fontSize: 11,
letterSpacing: '1px',
padding: '10px 15px',
textTransform: 'uppercase',
transition: 'opacity 0.3s',
opacity: 0.5,
maxHeight: 60,
overflow: 'hidden',
cursor: 'pointer',
background: 'transparent',
border: 'none',
},
activetab: {
opacity: 1,
},
};
class GroupTabs extends Component {
renderTab(name, group) {
let tabStyle = styles.tablink;
if (this.props.selectedGroup === name) {
tabStyle = Object.assign({}, styles.tablink, styles.activetab);
}
const onClick = e => {
e.preventDefault();
this.props.onGroupSelect(name);
};
let { title } = group;
if (typeof title === 'function') {
title = title();
}
return (
<button type="button" key={name} style={tabStyle} onClick={onClick} role="tab">
{title}
</button>
);
}
renderTabs() {
return Object.keys(this.props.groups).map(name => {
const group = this.props.groups[name];
return this.renderTab(name, group);
});
}
renderGroups() {
return Object.keys(this.props.groups)
.sort()
.map(name => {
const groupStyle = { display: 'none' };
const group = this.props.groups[name];
if (name === this.props.selectedGroup) {
Object.assign(groupStyle, { flex: 1, display: 'flex' });
}
return (
<div key={name} style={groupStyle}>
{group.render()}
</div>
);
});
}
renderEmpty() {
return <div style={styles.empty}>no groups available</div>;
}
render() {
if (!this.props.groups || !Object.keys(this.props.groups).length) {
return this.renderEmpty();
}
return (
<div style={styles.wrapper}>
<div style={styles.tabbar} role="tablist">
{this.renderTabs()}
</div>
<div style={styles.content}>{this.renderGroups()}</div>
</div>
);
}
}
GroupTabs.defaultProps = {
groups: {},
onGroupSelect: () => {},
selectedGroup: null,
};
GroupTabs.propTypes = {
groups: PropTypes.object, // eslint-disable-line react/forbid-prop-types
onGroupSelect: PropTypes.func,
selectedGroup: PropTypes.string,
};
export default GroupTabs;
|
packages/material-ui-icons/src/AlarmOffOutlined.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M10.04 6.29C10.66 6.11 11.32 6 12 6c3.86 0 7 3.14 7 7 0 .68-.11 1.34-.29 1.96l1.56 1.56c.47-1.08.73-2.27.73-3.52 0-4.97-4.03-9-9-9-1.25 0-2.44.26-3.53.72l1.57 1.57zM17.3365 1.811l4.6074 3.8436-1.2812 1.5358-4.6074-3.8436zM3.02 2.1L1.61 3.51l1.37 1.37-.92.77 1.28 1.54 1.06-.88.8.8C3.83 8.69 3 10.75 3 13c0 4.97 4.03 9 9 9 2.25 0 4.31-.83 5.89-2.2l2.1 2.1 1.41-1.41L3.02 2.1zM12 20c-3.86 0-7-3.14-7-7 0-1.7.61-3.26 1.62-4.47l9.85 9.85C15.26 19.39 13.7 20 12 20zM7.48 3.73l.46-.38-1.28-1.54-.6.5z" /></g></React.Fragment>
, 'AlarmOffOutlined');
|
src/components/StateComp2.js | nchathu2014/reactApp | import React from 'react';
export default class StateComp2 extends React.Component{
_handleOnClick(){
console.log("_handleOnClick fires");
}
render(){
var data = this.props.data;
return(
<div>
State 2 : {data} <br/>
<button onClick={this._handleOnClick}>Click Me</button>
</div>
);
}
} |
modules/RouteContext.js | mozillo/react-router | import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
}
}
export default RouteContext
|
examples/express-nunjucks-postcss-unstyled-react-webpack-mocha-sqlite-twitter/app/routes.js | sahat/megaboilerplate | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import App from './components/App';
import Home from './components/Home';
import Contact from './components/Contact';
import NotFound from './components/NotFound';
import Login from './components/Account/Login';
import Signup from './components/Account/Signup';
import Profile from './components/Account/Profile';
import Forgot from './components/Account/Forgot';
import Reset from './components/Account/Reset';
export default function getRoutes(store) {
const ensureAuthenticated = (nextState, replace) => {
if (!store.getState().auth.token) {
replace('/login');
}
};
const skipIfAuthenticated = (nextState, replace) => {
if (store.getState().auth.token) {
replace('/');
}
};
const clearMessages = () => {
store.dispatch({
type: 'CLEAR_MESSAGES'
});
};
return (
<Route path="/" component={App}>
<IndexRoute component={Home} onLeave={clearMessages}/>
<Route path="/contact" component={Contact} onLeave={clearMessages}/>
<Route path="/login" component={Login} onEnter={skipIfAuthenticated} onLeave={clearMessages}/>
<Route path="/signup" component={Signup} onEnter={skipIfAuthenticated} onLeave={clearMessages}/>
<Route path="/account" component={Profile} onEnter={ensureAuthenticated} onLeave={clearMessages}/>
<Route path="/forgot" component={Forgot} onEnter={skipIfAuthenticated} onLeave={clearMessages}/>
<Route path='/reset/:token' component={Reset} onEnter={skipIfAuthenticated} onLeave={clearMessages}/>
<Route path="*" component={NotFound} onLeave={clearMessages}/>
</Route>
);
}
|
blueprints/route/files/src/routes/__name__/components/__name__.js | easingthemes/easingthemes.github.io | import React from 'react'
import classes from './<%= pascalEntityName %>.scss'
export const <%= pascalEntityName %> = () => (
<div className={classes['<%= pascalEntityName %>']}>
<h4><%= pascalEntityName %></h4>
</div>
)
export default <%= pascalEntityName %>
|
docs/pages/examples/validation/index.js | Limenius/liform-react | import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { Provider } from 'react-redux'
import Liform from '../../../../src/'
import { SubmissionError } from 'redux-form'
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
function submit(values) {
return sleep(1000).then(() => {
// simulate server latency
if (!['john', 'paul', 'george', 'ringo'].includes(values.username)) {
throw new SubmissionError({
username: 'User does not exist',
_error: 'Login failed!'
})
} else if (values.password !== 'redux-form') {
throw new SubmissionError({
password: 'Wrong password',
_error: 'Login failed!'
})
} else {
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`)
}
})
}
const Demo = () => {
const reducer = combineReducers({ form: formReducer })
const store = createStore(reducer)
const schema = {
'type':'object',
'properties': {
'username': { 'type':'string', 'title': 'Username' },
'password': { 'type':'string', 'title': 'Password', 'widget': 'password' },
'email': { 'type':'string', 'format': 'email', 'title': 'E-mail', 'widget': 'email' },
}
}
return (
<Provider store={store}>
<Liform schema={schema} onSubmit={submit} />
</Provider>
)
}
ReactDOM.render(
<Demo/>,
document.getElementById('placeholder')
)
|
ajax/libs/clappr/0.0.31/clappr.js | tambien/cdnjs | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
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');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],2:[function(require,module,exports){
(function (process,global){
(function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function assertObject(x) {
if (!isObject(x))
throw $TypeError(x + ' is not an Object');
return x;
}
function setupGlobals(global) {
global.Symbol = Symbol;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
assertObject: assertObject,
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
var toObject = $traceurRuntime.toObject;
function spread() {
var rv = [],
k = 0;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = toObject(arguments[i]);
for (var j = 0; j < valueToSpread.length; j++) {
rv[k++] = valueToSpread[j];
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
}
if (superClass === null)
return null;
throw new $TypeError();
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw new Error(("\"" + action + "\" on closed generator"));
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime.assertObject($traceurRuntime),
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
return this.value_ = this.func.call(global);
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils";
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x | 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function toInteger(x) {
x = +x;
if (isNaN(x))
return 0;
if (!isFinite(x) || x === 0)
return x;
return x > 0 ? Math.floor(x) : Math.ceil(x);
}
var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH);
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array";
var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toInteger = $__3.toInteger,
toLength = $__3.toLength,
toObject = $__3.toObject,
isCallable = $__3.isCallable;
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
return {
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__5;
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator";
var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toObject = $__6.toObject,
toUint32 = $__6.toUint32;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__5, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__5), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map";
var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError("Constructor Map requires 'new'");
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError("Map can not be reentrantly initialised");
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
var iter = iterable[Symbol.iterator];
if (iter !== undefined) {
for (var $__8 = iterable[Symbol.iterator](),
$__9; !($__9 = $__8.next()).done; ) {
var $__10 = $traceurRuntime.assertObject($__9.value),
key = $__10[0],
value = $__10[1];
{
this.set(key, value);
}
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
}
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0,
len = this.entries_.length; i < len; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
}
}, {});
return {get Map() {
return Map;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object";
var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toInteger = $__11.toInteger,
toLength = $__11.toLength,
toObject = $__11.toObject,
isCallable = $__11.isCallable;
var $__11 = $traceurRuntime.assertObject($traceurRuntime),
defineProperty = $__11.defineProperty,
getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor,
getOwnPropertyNames = $__11.getOwnPropertyNames,
keys = $__11.keys,
privateNames = $__11.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
}
};
});
System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap";
var $__default = function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
scheduleFlush();
}
};
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
function useNextTick() {
return function() {
process.nextTick(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);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0],
arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise";
var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
cast: function(x) {
if (x instanceof this)
return x;
if (isPromise(x)) {
var result = getDeferred(this);
chain(x, result.resolve, result.reject);
return result.promise;
}
return this.resolve(x);
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
return {get Promise() {
return Promise;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String";
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills";
var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map;
var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")),
codePointAt = $__14.codePointAt,
contains = $__14.contains,
endsWith = $__14.endsWith,
fromCodePoint = $__14.fromCodePoint,
repeat = $__14.repeat,
raw = $__14.raw,
startsWith = $__14.startsWith;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")),
fill = $__14.fill,
find = $__14.find,
findIndex = $__14.findIndex;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")),
entries = $__14.entries,
keys = $__14.keys,
values = $__14.values;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")),
assign = $__14.assign,
is = $__14.is,
mixin = $__14.mixin;
function maybeDefineMethod(object, name, value) {
if (!(name in object)) {
Object.defineProperty(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
function polyfillCollections(global) {
if (!global.Map)
global.Map = Map;
}
function polyfillString(String) {
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
}
function polyfillArray(Array, Symbol) {
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
if (Symbol && Symbol.iterator) {
Object.defineProperty(Array.prototype, Symbol.iterator, {
value: values,
configurable: true,
enumerable: false,
writable: true
});
}
}
function polyfillObject(Object) {
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
function polyfill(global) {
polyfillPromise(global);
polyfillCollections(global);
polyfillString(global.String);
polyfillArray(global.Array, global.Symbol);
polyfillObject(global.Object);
}
polyfill(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfill(global);
};
return {};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import";
var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"));
return {};
});
System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + '');
}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"FWaASH":1}],3:[function(require,module,exports){
/*!
* jQuery JavaScript Library v2.1.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:11Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowclip^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// #11217 - WebKit loses check when the name is after the checked attribute
// Support: Windows Web Apps (WWA)
// `name` and `type` need .setAttribute for WWA
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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 = "*/".concat("*");
// #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,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// 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 );
}
return target;
}
/* Handles responses to an ajax request:
* - 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;
// 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
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else 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.unshift( tmp[ 1 ] );
}
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 };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
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"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": 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: {
url: true,
context: true
}
},
// 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 ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
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 transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// 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 is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.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,
// 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 == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// 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;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// 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 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;
}
}
}
// Callback for when everything is done
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;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// 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[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
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( isSuccess ? "ajaxSuccess" : "ajaxError",
[ 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");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
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({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// 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,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.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
overwritten = window[ callbackName ];
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";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
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";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( 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({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
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 !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// 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
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( 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
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
},{}],4:[function(require,module,exports){
/**
* Copyright 2012 Craig Campbell
*
* 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.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.1.2
* @url craig.is/killing/mice
*/
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
},
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
_KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
_SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
},
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
_SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc'
},
/**
* variable to store the flipped version of _MAP from above
* needed to check if we should use keypress or not when no action
* is specified
*
* @type {Object|undefined}
*/
_REVERSE_MAP,
/**
* a list of all the callbacks setup via Mousetrap.bind()
*
* @type {Object}
*/
_callbacks = {},
/**
* direct map of string combinations to callbacks used for trigger()
*
* @type {Object}
*/
_direct_map = {},
/**
* keeps track of what level each sequence is at since multiple
* sequences can start out with the same sequence
*
* @type {Object}
*/
_sequence_levels = {},
/**
* variable to store the setTimeout call
*
* @type {null|number}
*/
_reset_timer,
/**
* temporary state where we will ignore the next keyup
*
* @type {boolean|string}
*/
_ignore_next_keyup = false,
/**
* are we currently inside of a sequence?
* type of action ("keyup" or "keydown" or "keypress") or false
*
* @type {boolean|string}
*/
_inside_sequence = false;
/**
* loop through the f keys, f1 to f19 and add them to the map
* programatically
*/
for (var i = 1; i < 20; ++i) {
_MAP[111 + i] = 'f' + i;
}
/**
* loop through to map numbers on the numeric keypad
*/
for (i = 0; i <= 9; ++i) {
_MAP[i + 96] = i;
}
/**
* cross browser add event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _addEvent(object, type, callback) {
if (object.addEventListener) {
return object.addEventListener(type, callback, false);
}
object.attachEvent('on' + type, callback);
}
/**
* takes the event and returns the key character
*
* @param {Event} e
* @return {string}
*/
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
return String.fromCharCode(e.which);
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
return String.fromCharCode(e.which).toLowerCase();
}
/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @return {boolean}
*/
function _stop(e) {
var element = e.target || e.srcElement,
tag_name = element.tagName;
// if the element has the class "mousetrap" then no need to stop
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
return false;
}
// stop for input, select, and textarea
return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
}
/**
* checks if two arrays are equal
*
* @param {Array} modifiers1
* @param {Array} modifiers2
* @returns {boolean}
*/
function _modifiersMatch(modifiers1, modifiers2) {
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
}
/**
* resets all sequence counters except for the ones passed in
*
* @param {Object} do_not_reset
* @returns void
*/
function _resetSequences(do_not_reset) {
do_not_reset = do_not_reset || {};
var active_sequences = false,
key;
for (key in _sequence_levels) {
if (do_not_reset[key]) {
active_sequences = true;
continue;
}
_sequence_levels[key] = 0;
}
if (!active_sequences) {
_inside_sequence = false;
}
}
/**
* finds all callbacks that match based on the keycode, modifiers,
* and action
*
* @param {string} character
* @param {Array} modifiers
* @param {string} action
* @param {boolean=} remove - should we remove any matches
* @param {string=} combination
* @returns {Array}
*/
function _getMatches(character, modifiers, action, remove, combination) {
var i,
callback,
matches = [];
// if there are no events related to this keycode
if (!_callbacks[character]) {
return [];
}
// if a modifier key is coming up on its own we should allow it
if (action == 'keyup' && _isModifier(character)) {
modifiers = [character];
}
// loop through all callbacks for the key that was pressed
// and see if any of them match
for (i = 0; i < _callbacks[character].length; ++i) {
callback = _callbacks[character][i];
// if this is a sequence but it is not at the right level
// then move onto the next match
if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
continue;
}
// if the action we are looking for doesn't match the action we got
// then we should keep going
if (action != callback.action) {
continue;
}
// if this is a keypress event that means that we need to only
// look at the character, otherwise check the modifiers as
// well
if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
// remove is used so if you change your mind and call bind a
// second time with a new function the first one is overwritten
if (remove && callback.combo == combination) {
_callbacks[character].splice(i, 1);
}
matches.push(callback);
}
}
return matches;
}
/**
* takes a key event and figures out what the modifiers are
*
* @param {Event} e
* @returns {Array}
*/
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
/**
* actually calls the callback function
*
* if your callback function returns false this will use the jquery
* convention - prevent default and stop propogation on the event
*
* @param {Function} callback
* @param {Event} e
* @returns void
*/
function _fireCallback(callback, e) {
if (callback(e) === false) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
}
/**
* handles a character key event
*
* @param {string} character
* @param {Event} e
* @returns void
*/
function _handleCharacter(character, e) {
// if this event should not happen stop here
if (_stop(e)) {
return;
}
var callbacks = _getMatches(character, _eventModifiers(e), e.type),
i,
do_not_reset = {},
processed_sequence_callback = false;
// loop through matching callbacks for this key event
for (i = 0; i < callbacks.length; ++i) {
// fire for all sequence callbacks
// this is because if for example you have multiple sequences
// bound such as "g i" and "g t" they both need to fire the
// callback for matching g cause otherwise you can only ever
// match the first one
if (callbacks[i].seq) {
processed_sequence_callback = true;
// keep a list of which sequences were matches for later
do_not_reset[callbacks[i].seq] = 1;
_fireCallback(callbacks[i].callback, e);
continue;
}
// if there were no sequence matches but we are still here
// that means this is a regular match so we should fire that
if (!processed_sequence_callback && !_inside_sequence) {
_fireCallback(callbacks[i].callback, e);
}
}
// if you are inside of a sequence and the key you are pressing
// is not a modifier key then we should reset all sequences
// that were not matched by this key event
if (e.type == _inside_sequence && !_isModifier(character)) {
_resetSequences(do_not_reset);
}
}
/**
* handles a keydown event
*
* @param {Event} e
* @returns void
*/
function _handleKey(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
e.which = typeof e.which == "number" ? e.which : e.keyCode;
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
if (e.type == 'keyup' && _ignore_next_keyup == character) {
_ignore_next_keyup = false;
return;
}
_handleCharacter(character, e);
}
/**
* determines if the keycode specified is a modifier key or not
*
* @param {string} key
* @returns {boolean}
*/
function _isModifier(key) {
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
}
/**
* called to set a 1 second timeout on the specified sequence
*
* this is so after each key press in the sequence you have 1 second
* to press the next key before you have to start over
*
* @returns void
*/
function _resetSequenceTimer() {
clearTimeout(_reset_timer);
_reset_timer = setTimeout(_resetSequences, 1000);
}
/**
* reverses the map lookup so that we can look for specific keys
* to see what can and can't use keypress
*
* @return {Object}
*/
function _getReverseMap() {
if (!_REVERSE_MAP) {
_REVERSE_MAP = {};
for (var key in _MAP) {
// pull out the numeric keypad from here cause keypress should
// be able to detect the keys from the character
if (key > 95 && key < 112) {
continue;
}
if (_MAP.hasOwnProperty(key)) {
_REVERSE_MAP[_MAP[key]] = key;
}
}
}
return _REVERSE_MAP;
}
/**
* picks the best action based on the key combination
*
* @param {string} key - character for key
* @param {Array} modifiers
* @param {string=} action passed in
*/
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
/**
* binds a key sequence to an event
*
* @param {string} combo - combo specified in bind call
* @param {Array} keys
* @param {Function} callback
* @param {string=} action
* @returns void
*/
function _bindSequence(combo, keys, callback, action) {
// start off by adding a sequence level record for this combination
// and setting the level to 0
_sequence_levels[combo] = 0;
// if there is no action pick the best one for the first key
// in the sequence
if (!action) {
action = _pickBestAction(keys[0], []);
}
/**
* callback to increase the sequence level for this sequence and reset
* all other sequences that were active
*
* @param {Event} e
* @returns void
*/
var _increaseSequence = function(e) {
_inside_sequence = action;
++_sequence_levels[combo];
_resetSequenceTimer();
},
/**
* wraps the specified callback inside of another function in order
* to reset all sequence counters as soon as this sequence is done
*
* @param {Event} e
* @returns void
*/
_callbackAndReset = function(e) {
_fireCallback(callback, e);
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
_ignore_next_keyup = _characterFromEvent(e);
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(_resetSequences, 10);
},
i;
// loop through keys one at a time and bind the appropriate callback
// function. for any key leading up to the final one it should
// increase the sequence. after the final, it should reset all sequences
for (i = 0; i < keys.length; ++i) {
_bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
}
}
/**
* binds a single keyboard combination
*
* @param {string} combination
* @param {Function} callback
* @param {string=} action
* @param {string=} sequence_name - name of sequence if part of sequence
* @param {number=} level - what part of the sequence the command is
* @returns void
*/
function _bindSingle(combination, callback, action, sequence_name, level) {
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' '),
i,
key,
keys,
modifiers = [];
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
return _bindSequence(combination, sequence, callback, action);
}
// take the keys from this pattern and figure out what the actual
// pattern is all about
keys = combination === '+' ? ['+'] : combination.split('+');
for (i = 0; i < keys.length; ++i) {
key = keys[i];
// normalize key names
if (_SPECIAL_ALIASES[key]) {
key = _SPECIAL_ALIASES[key];
}
// if this is not a keypress event then we should
// be smart about using shift keys
// this will only work for US keyboards however
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
key = _SHIFT_MAP[key];
modifiers.push('shift');
}
// if this key is a modifier then add it to the list of modifiers
if (_isModifier(key)) {
modifiers.push(key);
}
}
// depending on what the key combination is
// we will try to pick the best event for it
action = _pickBestAction(key, modifiers, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
if (!_callbacks[key]) {
_callbacks[key] = [];
}
// remove an existing match if there is one
_getMatches(key, modifiers, action, !sequence_name, combination);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
_callbacks[key][sequence_name ? 'unshift' : 'push']({
callback: callback,
modifiers: modifiers,
action: action,
seq: sequence_name,
level: level,
combo: combination
});
}
/**
* binds multiple combinations to the same callback
*
* @param {Array} combinations
* @param {Function} callback
* @param {string|undefined} action
* @returns void
*/
function _bindMultiple(combinations, callback, action) {
for (var i = 0; i < combinations.length; ++i) {
_bindSingle(combinations[i], callback, action);
}
}
// start!
_addEvent(document, 'keypress', _handleKey);
_addEvent(document, 'keydown', _handleKey);
_addEvent(document, 'keyup', _handleKey);
var mousetrap = {
/**
* binds an event to mousetrap
*
* can be a single key, a combination of keys separated with +,
* a comma separated list of keys, an array of keys, or
* a sequence of keys separated by spaces
*
* be sure to list the modifier keys first to make sure that the
* correct key ends up getting bound (the last key in the pattern)
*
* @param {string|Array} keys
* @param {Function} callback
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
* @returns void
*/
bind: function(keys, callback, action) {
_bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
_direct_map[keys + ':' + action] = callback;
return this;
},
/**
* unbinds an event to mousetrap
*
* the unbinding sets the callback function of the specified key combo
* to an empty function and deletes the corresponding key in the
* _direct_map dict.
*
* the keycombo+action has to be exactly the same as
* it was defined in the bind method
*
* TODO: actually remove this from the _callbacks dictionary instead
* of binding an empty function
*
* @param {string|Array} keys
* @param {string} action
* @returns void
*/
unbind: function(keys, action) {
if (_direct_map[keys + ':' + action]) {
delete _direct_map[keys + ':' + action];
this.bind(keys, function() {}, action);
}
return this;
},
/**
* triggers an event that has already been bound
*
* @param {string} keys
* @param {string=} action
* @returns void
*/
trigger: function(keys, action) {
_direct_map[keys + ':' + action]();
return this;
},
/**
* resets the library back to its initial state. this is useful
* if you want to clear out the current keyboard shortcuts and bind
* new ones - for example if you switch to another page
*
* @returns void
*/
reset: function() {
_callbacks = {};
_direct_map = {};
return this;
}
};
module.exports = mousetrap;
},{}],5:[function(require,module,exports){
(function( factory ) {
if (typeof define !== 'undefined' && define.amd) {
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
var $ = require('jquery');
module.exports = factory( $ );
} else {
window.scrollMonitor = factory( jQuery );
}
})(function( $ ) {
var exports = {};
var $window = $(window);
var $document = $(document);
var watchers = [];
var VISIBILITYCHANGE = 'visibilityChange';
var ENTERVIEWPORT = 'enterViewport';
var FULLYENTERVIEWPORT = 'fullyEnterViewport';
var EXITVIEWPORT = 'exitViewport';
var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';
var LOCATIONCHANGE = 'locationChange';
var STATECHANGE = 'stateChange';
var eventTypes = [
VISIBILITYCHANGE,
ENTERVIEWPORT,
FULLYENTERVIEWPORT,
EXITVIEWPORT,
PARTIALLYEXITVIEWPORT,
LOCATIONCHANGE,
STATECHANGE
];
var defaultOffsets = {top: 0, bottom: 0};
exports.viewportTop;
exports.viewportBottom;
exports.documentHeight;
exports.viewportHeight = windowHeight();
var previousDocumentHeight;
var latestEvent;
function windowHeight() {
return window.innerHeight || document.documentElement.clientHeight;
}
var calculateViewportI;
function calculateViewport() {
exports.viewportTop = $window.scrollTop();
exports.viewportBottom = exports.viewportTop + exports.viewportHeight;
exports.documentHeight = $document.height();
if (exports.documentHeight !== previousDocumentHeight) {
calculateViewportI = watchers.length;
while( calculateViewportI-- ) {
watchers[calculateViewportI].recalculateLocation();
}
previousDocumentHeight = exports.documentHeight;
}
}
function recalculateWatchLocationsAndTrigger() {
exports.viewportHeight = windowHeight();
calculateViewport();
updateAndTriggerWatchers();
}
var recalculateAndTriggerTimer;
function debouncedRecalcuateAndTrigger() {
clearTimeout(recalculateAndTriggerTimer);
recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );
}
var updateAndTriggerWatchersI;
function updateAndTriggerWatchers() {
// update all watchers then trigger the events so one can rely on another being up to date.
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].update();
}
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].triggerCallbacks();
}
}
function ElementWatcher( watchItem, offsets ) {
var self = this;
this.watchItem = watchItem;
if (!offsets) {
this.offsets = defaultOffsets;
} else if (offsets === +offsets) {
this.offsets = {top: offsets, bottom: offsets};
} else {
this.offsets = $.extend({}, defaultOffsets, offsets);
}
this.callbacks = {}; // {callback: function, isOne: true }
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]] = [];
}
this.locked = false;
var wasInViewport;
var wasFullyInViewport;
var wasAboveViewport;
var wasBelowViewport;
var listenerToTriggerListI;
var listener;
function triggerCallbackArray( listeners ) {
if (listeners.length === 0) {
return;
}
listenerToTriggerListI = listeners.length;
while( listenerToTriggerListI-- ) {
listener = listeners[listenerToTriggerListI];
listener.callback.call( self, latestEvent );
if (listener.isOne) {
listeners.splice(listenerToTriggerListI, 1);
}
}
}
this.triggerCallbacks = function triggerCallbacks() {
if (this.isInViewport && !wasInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
}
if (this.isFullyInViewport && !wasFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
}
if (this.isAboveViewport !== wasAboveViewport &&
this.isBelowViewport !== wasBelowViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
// if you skip completely past this element
if (!wasFullyInViewport && !this.isFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!wasInViewport && !this.isInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
}
if (!this.isFullyInViewport && wasFullyInViewport) {
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!this.isInViewport && wasInViewport) {
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
if (this.isInViewport !== wasInViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
}
switch( true ) {
case wasInViewport !== this.isInViewport:
case wasFullyInViewport !== this.isFullyInViewport:
case wasAboveViewport !== this.isAboveViewport:
case wasBelowViewport !== this.isBelowViewport:
triggerCallbackArray( this.callbacks[STATECHANGE] );
}
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
};
this.recalculateLocation = function() {
if (this.locked) {
return;
}
var previousTop = this.top;
var previousBottom = this.bottom;
if (this.watchItem.nodeName) { // a dom element
var cachedDisplay = this.watchItem.style.display;
if (cachedDisplay === 'none') {
this.watchItem.style.display = '';
}
var elementLocation = $(this.watchItem).offset();
this.top = elementLocation.top;
this.bottom = elementLocation.top + this.watchItem.offsetHeight;
if (cachedDisplay === 'none') {
this.watchItem.style.display = cachedDisplay;
}
} else if (this.watchItem === +this.watchItem) { // number
if (this.watchItem > 0) {
this.top = this.bottom = this.watchItem;
} else {
this.top = this.bottom = exports.documentHeight - this.watchItem;
}
} else { // an object with a top and bottom property
this.top = this.watchItem.top;
this.bottom = this.watchItem.bottom;
}
this.top -= this.offsets.top;
this.bottom += this.offsets.bottom;
this.height = this.bottom - this.top;
if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {
triggerCallbackArray( this.callbacks[LOCATIONCHANGE] );
}
};
this.recalculateLocation();
this.update();
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
}
ElementWatcher.prototype = {
on: function( event, callback, isOne ) {
// trigger the event if it applies to the element right now.
switch( true ) {
case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:
case event === ENTERVIEWPORT && this.isInViewport:
case event === FULLYENTERVIEWPORT && this.isFullyInViewport:
case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:
case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:
callback();
if (isOne) {
return;
}
}
if (this.callbacks[event]) {
this.callbacks[event].push({callback: callback, isOne: isOne});
} else {
throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
off: function( event, callback ) {
if (this.callbacks[event]) {
for (var i = 0, item; item = this.callbacks[event][i]; i++) {
if (item.callback === callback) {
this.callbacks[event].splice(i, 1);
break;
}
}
} else {
throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
one: function( event, callback ) {
this.on( event, callback, true);
},
recalculateSize: function() {
this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;
this.bottom = this.top + this.height;
},
update: function() {
this.isAboveViewport = this.top < exports.viewportTop;
this.isBelowViewport = this.bottom > exports.viewportBottom;
this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);
this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||
(this.isAboveViewport && this.isBelowViewport);
},
destroy: function() {
var index = watchers.indexOf(this),
self = this;
watchers.splice(index, 1);
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]].length = 0;
}
},
// prevent recalculating the element location
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
}
};
var eventHandlerFactory = function (type) {
return function( callback, isOne ) {
this.on.call(this, type, callback, isOne);
};
};
for (var i = 0, j = eventTypes.length; i < j; i++) {
var type = eventTypes[i];
ElementWatcher.prototype[type] = eventHandlerFactory(type);
}
try {
calculateViewport();
} catch (e) {
$(calculateViewport);
}
function scrollMonitorListener(event) {
latestEvent = event;
calculateViewport();
updateAndTriggerWatchers();
}
$window.on('scroll', scrollMonitorListener);
$window.on('resize', debouncedRecalcuateAndTrigger);
exports.beget = exports.create = function( element, offsets ) {
if (typeof element === 'string') {
element = $(element)[0];
}
if (element instanceof $) {
element = element[0];
}
var watcher = new ElementWatcher( element, offsets );
watchers.push(watcher);
watcher.update();
return watcher;
};
exports.update = function() {
latestEvent = null;
calculateViewport();
updateAndTriggerWatchers();
};
exports.recalculateLocations = function() {
exports.documentHeight = 0;
exports.update();
};
return exports;
});
},{"jquery":3}],6:[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return obj.length === +obj.length ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(slice.call(arguments, 1), true, true, []);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],"base_object":[function(require,module,exports){
module.exports=require('2HNVgz');
},{}],"2HNVgz":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = require('./utils').extend;
var Events = require('./events');
var pluginOptions = ['container'];
var BaseObject = function BaseObject(options) {
this.uniqueId = _.uniqueId('o');
options || (options = {});
_.extend(this, _.pick(options, pluginOptions));
};
($traceurRuntime.createClass)(BaseObject, {}, {}, Events);
BaseObject.extend = extend;
module.exports = BaseObject;
},{"./events":13,"./utils":23,"underscore":6}],"6xH8xW":[function(require,module,exports){
"use strict";
var BaseObject = require('./base_object');
var ContainerPlugin = function ContainerPlugin(options) {
$traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]);
this.bindEvents();
};
var $ContainerPlugin = ContainerPlugin;
($traceurRuntime.createClass)(ContainerPlugin, {
enable: function() {
this.bindEvents();
},
disable: function() {
this.stopListening();
},
bindEvents: function() {}
}, {}, BaseObject);
module.exports = ContainerPlugin;
},{"./base_object":"2HNVgz"}],"container_plugin":[function(require,module,exports){
module.exports=require('6xH8xW');
},{}],"core_plugin":[function(require,module,exports){
module.exports=require('it+usN');
},{}],"it+usN":[function(require,module,exports){
"use strict";
var BaseObject = require('./base_object');
var CorePlugin = function CorePlugin(core) {
$traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]);
this.core = core;
};
var $CorePlugin = CorePlugin;
($traceurRuntime.createClass)(CorePlugin, {getExternalInterface: function() {
return {};
}}, {}, BaseObject);
module.exports = CorePlugin;
},{"./base_object":"2HNVgz"}],13:[function(require,module,exports){
(function (global){
"use strict";
var _ = require('underscore');
var Log = require('../plugins/log');
var slice = Array.prototype.slice;
var Events = function Events() {};
($traceurRuntime.createClass)(Events, {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain,
ev,
events,
names,
i,
l,
j,
k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
events = this._events[name];
if (events) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length)
delete this._events[name];
}
}
return this;
},
trigger: function(name) {
var klass = arguments[arguments.length - 1];
if (global.DEBUG) {
if (Log.BLACKLIST.indexOf(name) < 0)
Log.info(klass, 'event ' + name + ' triggered');
}
if (!this._events)
return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args))
return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events)
triggerEvents(events, args);
if (allEvents)
triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo)
return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object')
callback = this;
if (obj)
(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events))
delete this._listeningTo[id];
}
return this;
}
}, {});
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name)
return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0,
l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev,
i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)
(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
_.each(listenMethods, function(implementation, method) {
Events.prototype[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object')
callback = this;
obj[implementation](name, callback, this);
return this;
};
});
module.exports = Events;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../plugins/log":59,"underscore":6}],14:[function(require,module,exports){
"use strict";
var _ = require('underscore');
module.exports = {
'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls> <% var renderBar = function(name) { %> <div class="bar-container" data-<%= name %>> <div class="bar-background" data-<%= name %>> <div class="bar-fill-1" data-<%= name %>></div> <div class="bar-fill-2" data-<%= name %>></div> <div class="bar-hover" data-<%= name %>></div> </div> <div class="bar-scrubber" data-<%= name %>> <div class="bar-scrubber-icon" data-<%= name %>></div> </div> </div> <% }; %> <% var renderDrawer = function(name, renderContent) { %> <div class="drawer-container" data-<%= name %>> <div class="drawer-icon-container" data-<%= name %>> <div class="drawer-icon media-control-icon" data-<%= name %>></div> <span class="drawer-text" data-<%= name %>></span> </div> <% renderContent(name); %> </div> <% }; %> <% var renderIndicator = function(name) { %> <div class="media-control-indicator" data-<%= name %>></div> <% }; %> <% var renderButton = function(name) { %> <button class="media-control-button media-control-icon" data-<%= name %>></button> <% }; %> <% var render = function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.default && settings.default.length) { %> <div class="media-control-center-panel" data-media-control> <% render(settings.default); %> </div> <% } %> <% if (settings.left && settings.left.length) { %> <div class="media-control-left-panel" data-media-control> <% render(settings.left); %> </div> <% } %> <% if (settings.right && settings.right.length) { %> <div class="media-control-right-panel" data-media-control> <% render(settings.right); %> </div> <% } %></div>'),
'seek_time': _.template('<span data-seek-time></span>'),
'flash': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'),
'hls': _.template(' <param name="movie" value="<%= swfPath %>?inline=1"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'),
'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'),
'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'),
'background_button': _.template('<div class="playpause-button-wrapper" data-background-button> <span class="playpause-icon" data-background-button></span></div>'),
'poster': _.template('<div class="play-wrapper" data-poster> <span class="poster-icon play" data-poster /></div>'),
'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'),
'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'),
CSS: {
'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}',
'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-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);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}',
'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;border-radius:0;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto;max-width:100%;min-width:60%;height:40px;z-index:9999;-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:150px;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:all,.6s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.6s,ease-out;-o-transition:all,.6s,ease-out;transition:all,.6s,ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.5) 0 0 15px;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control].media-control-hide{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-background[data-background],.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:relative;top:10%;height:80%;vertical-align:middle}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:10px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin-right:3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:none;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5)}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:block}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all,.2s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.2s,ease-out;-o-transition:all,.2s,ease-out;transition:all,.2s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}',
'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',
'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',
'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',
'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',
'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}',
'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.background-button[data-background-button].hide[data-background-button]{opacity:0}.background-button[data-background-button] .playpause-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:20%;top:45%;margin-top:-5%;text-align:center}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]{font-family:Player;cursor:pointer;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;font-size:90px;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]:hover{text-shadow:rgba(255,255,255,.5) 0 0 15px}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].paused:before{content:"\\e001"}',
'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;overflow:hidden;width:100%;height:20%;line-height:100%;font-size:20%;top:50%;margin-top:-5%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}',
'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',
'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'
}
};
},{"underscore":6}],"VbgHr3":[function(require,module,exports){
"use strict";
var UIObject = require('../base/ui_object');
var Playback = function Playback(options) {
$traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]);
this.settings = {};
};
var $Playback = Playback;
($traceurRuntime.createClass)(Playback, {
play: function() {},
pause: function() {},
stop: function() {},
seek: function(time) {},
getDuration: function() {
return 0;
},
isPlaying: function() {
return false;
},
getPlaybackType: function() {
return 'no_op';
},
isHighDefinitionInUse: function() {
return false;
},
volume: function(value) {},
destroy: function() {
this.$el.remove();
}
}, {}, UIObject);
Playback.canPlay = (function(source) {
return false;
});
module.exports = Playback;
},{"../base/ui_object":22}],"playback":[function(require,module,exports){
module.exports=require('VbgHr3');
},{}],17:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var JST = require('./jst');
var Styler = {getStyleFor: function(name, options) {
options = options || {};
return $('<style></style>').html(_.template(JST.CSS[name])(options));
}};
module.exports = Styler;
},{"./jst":14,"jquery":3,"underscore":6}],"ui_container_plugin":[function(require,module,exports){
module.exports=require('XSLDWT');
},{}],"XSLDWT":[function(require,module,exports){
"use strict";
var UIObject = require('./ui_object');
var UIContainerPlugin = function UIContainerPlugin(options) {
$traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]);
this.enabled = true;
this.bindEvents();
};
var $UIContainerPlugin = UIContainerPlugin;
($traceurRuntime.createClass)(UIContainerPlugin, {
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
bindEvents: function() {}
}, {}, UIObject);
module.exports = UIContainerPlugin;
},{"./ui_object":22}],"ui_core_plugin":[function(require,module,exports){
module.exports=require('gNZMEo');
},{}],"gNZMEo":[function(require,module,exports){
"use strict";
var UIObject = require('./ui_object');
var UICorePlugin = function UICorePlugin(core) {
$traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]);
this.core = core;
this.enabled = true;
this.bindEvents();
this.render();
};
var $UICorePlugin = UICorePlugin;
($traceurRuntime.createClass)(UICorePlugin, {
bindEvents: function() {},
getExternalInterface: function() {
return {};
},
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
render: function() {
this.$el.html(this.template());
this.$el.append(this.styler.getStyleFor(this.name));
this.core.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = UICorePlugin;
},{"./ui_object":22}],22:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var extend = require('./utils').extend;
var BaseObject = require('./base_object');
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var UIObject = function UIObject(options) {
$traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]);
this.cid = _.uniqueId('c');
this._ensureElement();
this.delegateEvents();
};
var $UIObject = UIObject;
($traceurRuntime.createClass)(UIObject, {
get tagName() {
return 'div';
},
$: function(selector) {
return this.$el.find(selector);
},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
setElement: function(element, delegate) {
if (this.$el)
this.undelegateEvents();
this.$el = element instanceof $ ? element : $(element);
this.el = this.$el[0];
if (delegate !== false)
this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events'))))
return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method))
method = this[events[key]];
if (!method)
continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id)
attrs.id = _.result(this, 'id');
if (this.className)
attrs['class'] = _.result(this, 'className');
var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
}, {}, BaseObject);
UIObject.extend = extend;
module.exports = UIObject;
},{"./base_object":"2HNVgz","./utils":23,"jquery":3,"underscore":6}],23:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps)
_.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
child.super = function(name) {
return parent.prototype[name];
};
child.prototype.getClass = function() {
return child;
};
return child;
};
var zeroPad = function(number, size) {
return (new Array(size + 1 - number.toString().length)).join('0') + number;
};
var formatTime = function(time) {
time = time * 1000;
time = parseInt(time / 1000);
var seconds = time % 60;
time = parseInt(time / 60);
var minutes = time % 60;
time = parseInt(time / 60);
var hours = time % 24;
var out = "";
if (hours && hours > 0)
out += ("0" + hours).slice(-2) + ":";
out += ("0" + minutes).slice(-2) + ":";
out += ("0" + seconds).slice(-2);
return out.trim();
};
var Fullscreen = {
isFullscreen: function() {
return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement;
},
requestFullscreen: function(el) {
if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
},
cancelFullscreen: function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
};
var HEX_TAB = "0123456789abcdef";
var B64_TAB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
var b64pad = "";
var rstr2b64 = function(input) {
var output = "";
var len = input.length;
for (var i = 0; i < len; i += 3) {
var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > input.length * 8)
output += b64pad;
else
output += B64_TAB.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
}
}
return output;
};
var rstr2hex = function(input) {
var output = "";
for (var i = 0; i < input.length; i++) {
var x = input.charCodeAt(i);
output += HEX_TAB.charAt((x >>> 4) & 0x0F) + HEX_TAB.charAt(x & 0x0F);
}
return output;
};
var getHostname = function() {
return location.hostname;
};
var Ajax = {
jsonp: function(settings) {
var defer = new $.Deferred();
settings.callbackName = settings.callbackName || "json_callback";
settings.timeout = settings.timeout || 15000;
window[settings.callbackName] = function(data) {
if (!Ajax.isErrorObject(data)) {
defer.resolve(data);
} else {
defer.reject(data);
}
};
var head = $("head")[0];
var script = document.createElement("script");
script.setAttribute("src", settings.url);
script.setAttribute("async", "async");
script.onload = script.onreadystatechange = function(eventLoad) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (settings.timeoutId) {
window.clearTimeout(settings.timeoutId);
}
script.onload = script.onreadystatechange = null;
if (head && script.parentNode)
head.removeChild(script);
script = undefined;
}
};
head.insertBefore(script, head.firstChild);
if (settings.error) {
settings.timeoutId = window.setTimeout(settings.error, settings.timeout);
}
return defer.promise();
},
isErrorObject: function(data) {
return data && data.http_status_code && data.http_status_code != 200;
}
};
module.exports = {
extend: extend,
zeroPad: zeroPad,
formatTime: formatTime,
Fullscreen: Fullscreen,
Ajax: Ajax,
rstr2b64: rstr2b64,
rstr2hex: rstr2hex,
getHostname: getHostname
};
},{"jquery":3,"underscore":6}],"195Wj5":[function(require,module,exports){
"use strict";
var Browser = function Browser() {};
($traceurRuntime.createClass)(Browser, {}, {});
Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);
Browser.isChrome = !!(navigator.userAgent.match(/chrome/i));
Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i));
Browser.isLegacyIE = !!(window.ActiveXObject);
Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i));
Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));
Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));
module.exports = Browser;
},{}],"browser":[function(require,module,exports){
module.exports=require('195Wj5');
},{}],26:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var _ = require('underscore');
var Container = function Container(options) {
$traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]);
this.playback = options.playback;
this.settings = this.playback.settings;
this.isReady = false;
this.mediaControlDisabled = false;
this.plugins = [this.playback];
this.bindEvents();
};
var $Container = Container;
($traceurRuntime.createClass)(Container, {
get name() {
return 'Container';
},
get attributes() {
return {'data-container': ''};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.playback, 'playback:progress', this.progress);
this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated);
this.listenTo(this.playback, 'playback:ready', this.ready);
this.listenTo(this.playback, 'playback:buffering', this.buffering);
this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull);
this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate);
this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata);
this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged);
this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged);
this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl);
this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl);
this.listenTo(this.playback, 'playback:ended', this.ended);
this.listenTo(this.playback, 'playback:play', this.playing);
},
with: function(klass) {
_.extend(this, klass);
return this;
},
playbackStateChanged: function() {
this.trigger('container:playbackstate');
},
playbackDvrStateChanged: function(dvrInUse) {
this.settings = this.playback.settings;
this.trigger('container:dvr', dvrInUse);
},
statsAdd: function(metric) {
this.trigger('container:stats:add', metric);
},
statsReport: function(metrics) {
this.trigger('container:stats:report', metrics);
},
getPlaybackType: function() {
return this.playback.getPlaybackType();
},
destroy: function() {
this.trigger('container:destroyed', this, this.name);
this.playback.destroy();
this.$el.remove();
},
setStyle: function(style) {
this.$el.css(style);
},
animate: function(style, duration) {
return this.$el.animate(style, duration).promise();
},
ready: function() {
this.isReady = true;
this.trigger('container:ready', this.name);
},
isPlaying: function() {
return this.playback.isPlaying();
},
getDuration: function() {
return this.playback.getDuration();
},
error: function(errorObj) {
this.trigger('container:error', errorObj, this.name);
},
loadedMetadata: function(duration) {
this.trigger('container:loadedmetadata', duration);
},
timeUpdated: function(position, duration) {
this.trigger('container:timeupdate', position, duration, this.name);
},
progress: function(startPosition, endPosition, duration) {
this.trigger('container:progress', startPosition, endPosition, duration, this.name);
},
playing: function() {
this.trigger('container:play', this.name);
},
play: function() {
this.playback.play();
},
stop: function() {
this.trigger('container:stop', this.name);
this.playback.stop();
},
pause: function() {
this.trigger('container:pause', this.name);
this.playback.pause();
},
ended: function() {
this.trigger('container:ended', this, this.name);
},
clicked: function() {
this.trigger('container:click', this, this.name);
},
setCurrentTime: function(time) {
this.trigger('container:seek', time, this.name);
this.playback.seek(time);
},
setVolume: function(value) {
this.trigger('container:volume', value, this.name);
this.playback.volume(value);
},
requestFullscreen: function() {
this.trigger('container:fullscreen', this.name);
},
buffering: function() {
this.trigger('container:state:buffering', this.name);
},
bufferfull: function() {
this.trigger('container:state:bufferfull', this.name);
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find(function(plugin) {
return plugin.name === name;
});
},
settingsUpdate: function() {
this.settings = this.playback.settings;
this.trigger('container:settingsupdate');
},
highDefinitionUpdate: function() {
this.trigger('container:highdefinitionupdate');
},
isHighDefinitionInUse: function() {
return this.playback.isHighDefinitionInUse();
},
disableMediaControl: function() {
this.mediaControlDisabled = true;
this.trigger('container:mediacontrol:disable');
},
enableMediaControl: function() {
this.mediaControlDisabled = false;
this.trigger('container:mediacontrol:enable');
},
render: function() {
var style = Styler.getStyleFor('container');
this.$el.append(style);
this.$el.append(this.playback.render().el);
return this;
}
}, {}, UIObject);
module.exports = Container;
},{"../../base/styler":17,"../../base/ui_object":22,"underscore":6}],27:[function(require,module,exports){
"use strict";
module.exports = require('./container');
},{"./container":26}],28:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('../../base/base_object');
var Container = require('../container');
var $ = require('jquery');
var ContainerFactory = function ContainerFactory(options, loader) {
$traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]);
this.options = options;
this.loader = loader;
};
var $ContainerFactory = ContainerFactory;
($traceurRuntime.createClass)(ContainerFactory, {
createContainers: function() {
return $.Deferred(function(promise) {
promise.resolve(_.map(this.options.sources, function(source) {
return this.createContainer(source);
}, this));
}.bind(this));
},
findPlaybackPlugin: function(source) {
return _.find(this.loader.playbackPlugins, (function(p) {
return p.canPlay(source.toString());
}), this);
},
createContainer: function(source) {
var playbackPlugin = this.findPlaybackPlugin(source);
var options = _.extend({}, this.options, {
src: source,
autoPlay: !!this.options.autoPlay
});
var playback = new playbackPlugin(options);
var container = new Container({playback: playback});
var defer = $.Deferred();
defer.promise(container);
this.addContainerPlugins(container, source);
this.listenToOnce(container, 'container:ready', (function() {
return defer.resolve(container);
}));
return container;
},
addContainerPlugins: function(container, source) {
_.each(this.loader.containerPlugins, function(Plugin) {
var options = _.extend(this.options, {
container: container,
src: source
});
container.addPlugin(new Plugin(options));
}, this);
}
}, {}, BaseObject);
module.exports = ContainerFactory;
},{"../../base/base_object":"2HNVgz","../container":27,"jquery":3,"underscore":6}],29:[function(require,module,exports){
"use strict";
module.exports = require('./container_factory');
},{"./container_factory":28}],30:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var UIObject = require('../../base/ui_object');
var ContainerFactory = require('../container_factory');
var Fullscreen = require('../../base/utils').Fullscreen;
var Styler = require('../../base/styler');
var MediaControl = require('../media_control');
var PlayerInfo = require('../player_info');
var Mediator = require('../mediator');
var Core = function Core(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]);
this.playerInfo = PlayerInfo.getInstance();
this.playerInfo.options = options;
this.options = options;
this.plugins = [];
this.containers = [];
this.createContainers(options);
this.updateSize();
document.addEventListener('fullscreenchange', (function() {
return $__0.exit();
}));
document.addEventListener('MSFullscreenChange', (function() {
return $__0.exit();
}));
document.addEventListener('mozfullscreenchange', (function() {
return $__0.exit();
}));
$(window).resize((function() {
return $__0.updateSize();
}));
};
var $Core = Core;
($traceurRuntime.createClass)(Core, {
get events() {
return {
'webkitfullscreenchange': 'exit',
'mousemove': 'showMediaControl',
'mouseleave': 'hideMediaControl'
};
},
get attributes() {
return {'data-player': ''};
},
createContainers: function(options) {
var $__0 = this;
this.defer = $.Deferred();
this.defer.promise(this);
this.containerFactory = new ContainerFactory(options, options.loader);
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
})).then((function(containers) {
return $__0.resolveOnContainersReady(containers);
}));
},
updateSize: function() {
if (Fullscreen.isFullscreen()) {
this.$el.addClass('fullscreen');
this.$el.removeAttr('style');
this.playerInfo.currentSize = {
width: window.innerWidth,
height: window.innerHeight
};
} else {
var needStretch = !!this.options.stretchWidth && !!this.options.stretchHeight;
var width,
height;
if (needStretch && this.options.stretchWidth <= window.innerWidth && this.options.stretchHeight <= (window.innerHeight * 0.73)) {
width = this.options.stretchWidth;
height = this.options.stretchHeight;
} else {
width = this.options.width;
height = this.options.height;
}
this.$el.css({width: width});
this.$el.css({height: height});
this.$el.removeClass('fullscreen');
this.playerInfo.currentSize = {
width: width,
height: height
};
}
Mediator.trigger('player:resize');
},
resolveOnContainersReady: function(containers) {
var $__0 = this;
$.when.apply($, containers).done((function() {
return $__0.defer.resolve($__0);
}));
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find((function(plugin) {
return plugin.name === name;
}));
},
load: function(sources) {
var $__0 = this;
sources = _.isString(sources) ? [sources] : sources;
_(this.containers).each((function(container) {
return container.destroy();
}));
this.containerFactory.options = _(this.options).extend({sources: sources});
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
}));
},
destroy: function() {
_(this.containers).each((function(container) {
return container.destroy();
}));
this.$el.remove();
},
exit: function() {
this.updateSize();
this.mediaControl.show();
},
setMediaControlContainer: function(container) {
this.mediaControl.setContainer(container);
this.mediaControl.render();
},
disableMediaControl: function() {
this.mediaControl.disable();
this.$el.removeClass('nocursor');
},
enableMediaControl: function() {
this.mediaControl.enable();
},
removeContainer: function(container) {
this.stopListening(container);
this.containers = _.without(this.containers, container);
},
appendContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.el.appendChild(container.render().el);
this.containers.push(container);
},
prependContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.$el.append(container.render().el);
this.containers.unshift(container);
},
setupContainers: function(containers) {
_.map(containers, this.appendContainer, this);
this.setupMediaControl(this.getCurrentContainer());
this.render();
this.$el.appendTo(this.options.parentElement);
return containers;
},
createContainer: function(source) {
var container = this.containerFactory.createContainer(source);
this.appendContainer(container);
return container;
},
setupMediaControl: function(container) {
if (this.mediaControl) {
this.mediaControl.setContainer(container);
} else {
this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));
this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen);
this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true));
this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false));
}
},
createMediaControl: function(options) {
if (options.mediacontrol && options.mediacontrol.external) {
return new options.mediacontrol.external(options);
} else {
return new MediaControl(options);
}
},
getCurrentContainer: function() {
return this.containers[0];
},
toggleFullscreen: function() {
if (!Fullscreen.isFullscreen()) {
Fullscreen.requestFullscreen(this.el);
this.$el.addClass('fullscreen');
} else {
Fullscreen.cancelFullscreen();
this.$el.removeClass('fullscreen nocursor');
}
this.mediaControl.show();
},
showMediaControl: function(event) {
this.mediaControl.show(event);
},
hideMediaControl: function(event) {
this.mediaControl.hide(event);
},
onMediaControlShow: function(showing) {
if (showing)
this.$el.removeClass('nocursor');
else if (Fullscreen.isFullscreen())
this.$el.addClass('nocursor');
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor('core');
this.$el.append(style);
this.$el.append(this.mediaControl.render().el);
this.$el.ready((function() {
$__0.options.width = $__0.options.width || $__0.$el.width();
$__0.options.height = $__0.options.height || $__0.$el.height();
$__0.updateSize();
}));
return this;
}
}, {}, UIObject);
module.exports = Core;
},{"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23,"../container_factory":29,"../media_control":"A8Uh+k","../mediator":"veeMMc","../player_info":"Pce0iO","jquery":3,"underscore":6}],31:[function(require,module,exports){
"use strict";
module.exports = require('./core');
},{"./core":30}],32:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('../../base/base_object');
var Core = require('../core');
var CoreFactory = function CoreFactory(player, loader) {
this.player = player;
this.options = player.options;
this.loader = loader;
this.options.loader = this.loader;
};
($traceurRuntime.createClass)(CoreFactory, {
create: function() {
this.core = new Core(this.options);
this.core.then(this.addCorePlugins.bind(this));
return this.core;
},
addCorePlugins: function() {
_.each(this.loader.corePlugins, function(Plugin) {
var plugin = new Plugin(this.core);
this.core.addPlugin(plugin);
this.setupExternalInterface(plugin);
}, this);
return this.core;
},
setupExternalInterface: function(plugin) {
_.each(plugin.getExternalInterface(), function(value, key) {
this.player[key] = value.bind(plugin);
}, this);
}
}, {}, BaseObject);
module.exports = CoreFactory;
},{"../../base/base_object":"2HNVgz","../core":31,"underscore":6}],33:[function(require,module,exports){
"use strict";
module.exports = require('./core_factory');
},{"./core_factory":32}],34:[function(require,module,exports){
"use strict";
module.exports = require('./loader');
},{"./loader":35}],35:[function(require,module,exports){
"use strict";
var BaseObject = require('../../base/base_object');
var _ = require('underscore');
var PlayerInfo = require('../player_info');
var HTML5VideoPlayback = require('../../playbacks/html5_video');
var FlashVideoPlayback = require('../../playbacks/flash');
var HTML5AudioPlayback = require('../../playbacks/html5_audio');
var HLSVideoPlayback = require('../../playbacks/hls');
var NoOp = require('../../playbacks/no_op');
var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');
var StatsPlugin = require('../../plugins/stats');
var WaterMarkPlugin = require('../../plugins/watermark');
var PosterPlugin = require('../../plugins/poster');
var BackgroundButton = require('../../plugins/background_button');
var Loader = function Loader(externalPlugins) {
$traceurRuntime.superCall(this, $Loader.prototype, "constructor", []);
this.playerInfo = PlayerInfo.getInstance();
this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp];
this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin];
this.corePlugins = [BackgroundButton];
if (externalPlugins) {
this.addExternalPlugins(externalPlugins);
}
};
var $Loader = Loader;
($traceurRuntime.createClass)(Loader, {
addExternalPlugins: function(plugins) {
var pluginName = function(plugin) {
return plugin.prototype.name;
};
if (plugins.playback) {
this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);
}
if (plugins.container) {
this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);
}
if (plugins.core) {
this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);
}
this.playerInfo.playbackPlugins = this.playbackPlugins;
},
getPlugin: function(name) {
var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);
return _.find(allPlugins, function(plugin) {
return plugin.prototype.name === name;
});
}
}, {}, BaseObject);
module.exports = Loader;
},{"../../base/base_object":"2HNVgz","../../playbacks/flash":48,"../../playbacks/hls":50,"../../playbacks/html5_audio":52,"../../playbacks/html5_video":54,"../../playbacks/no_op":55,"../../plugins/background_button":58,"../../plugins/poster":61,"../../plugins/spinner_three_bounce":63,"../../plugins/stats":65,"../../plugins/watermark":67,"../player_info":"Pce0iO","underscore":6}],"A8Uh+k":[function(require,module,exports){
"use strict";
module.exports = require('./media_control');
},{"./media_control":38}],"media_control":[function(require,module,exports){
module.exports=require('A8Uh+k');
},{}],38:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var UIObject = require('../../base/ui_object');
var Utils = require('../../base/utils');
var Mousetrap = require('mousetrap');
var SeekTime = require('../seek_time');
var transitionEvents = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend';
var MediaControl = function MediaControl(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]);
this.seekTime = new SeekTime(this);
this.options = options;
this.currentVolume = this.options.mute ? 0 : 100;
this.container = options.container;
this.container.setVolume(this.currentVolume);
this.keepVisible = false;
this.addEventListeners();
this.settings = {
left: ['play', 'stop', 'pause'],
right: ['volume'],
default: ['position', 'seekbar', 'duration']
};
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.disabled = false;
if (this.container.mediaControlDisabled || this.options.chromeless) {
this.disable();
}
$(document).bind('mouseup', (function(event) {
return $__0.stopDrag(event);
}));
$(document).bind('mousemove', (function(event) {
return $__0.updateDrag(event);
}));
};
var $MediaControl = MediaControl;
($traceurRuntime.createClass)(MediaControl, {
get name() {
return 'MediaControl';
},
get attributes() {
return {
class: 'media-control',
'data-media-control': ''
};
},
get events() {
return {
'click [data-play]': 'play',
'click [data-pause]': 'pause',
'click [data-playpause]': 'togglePlayPause',
'click [data-stop]': 'stop',
'click [data-playstop]': 'togglePlayStop',
'click [data-fullscreen]': 'toggleFullscreen',
'click [data-seekbar]': 'seek',
'click .bar-background[data-volume]': 'volume',
'click .drawer-icon[data-volume]': 'toggleMute',
'mouseover .drawer-container[data-volume]': 'showVolumeBar',
'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',
'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',
'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',
'mouseenter .bar-container[data-volume]': 'mousemoveOnSeekBar',
'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',
'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',
'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',
'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'
};
},
get template() {
return JST.media_control;
},
addEventListeners: function() {
this.listenTo(this.container, 'container:play', this.changeTogglePlay);
this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar);
this.listenTo(this.container, 'container:progress', this.updateProgressBar);
this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.container, 'container:mediacontrol:disable', this.disable);
this.listenTo(this.container, 'container:mediacontrol:enable', this.enable);
this.listenTo(this.container, 'container:ended', this.ended);
},
disable: function() {
this.disabled = true;
this.hide();
this.$el.hide();
},
enable: function() {
if (this.options.chromeless)
return;
this.disabled = false;
this.show();
},
play: function() {
this.container.play();
},
pause: function() {
this.container.pause();
},
stop: function() {
this.container.stop();
},
changeTogglePlay: function() {
if (this.container.isPlaying()) {
this.$playPauseToggle.removeClass('paused').addClass('playing');
this.$playStopToggle.removeClass('stopped').addClass('playing');
this.trigger('mediacontrol:playing');
} else {
this.$playPauseToggle.removeClass('playing').addClass('paused');
this.$playStopToggle.removeClass('playing').addClass('stopped');
this.trigger('mediacontrol:notplaying');
}
},
mousemoveOnSeekBar: function(event) {
if (this.container.settings.seekEnabled) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);
this.$seekBarHover.css({left: offsetX});
this.$seekBarHover.show();
}
this.trigger('mediacontrol:mousemove:seekbar', event);
},
mouseleaveOnSeekBar: function(event) {
this.$seekBarHover.hide();
this.trigger('mediacontrol:mouseleave:seekbar', event);
},
togglePlayPause: function() {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
this.changeTogglePlay();
},
togglePlayStop: function() {
if (this.container.isPlaying()) {
this.container.stop();
} else {
this.container.play();
}
this.changeTogglePlay();
},
startSeekDrag: function(event) {
if (!this.container.settings.seekEnabled)
return;
this.draggingSeekBar = true;
this.$seekBarLoaded.addClass('media-control-notransition');
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (event) {
event.preventDefault();
}
},
startVolumeDrag: function(event) {
this.draggingVolumeBar = true;
if (event) {
event.preventDefault();
}
},
stopDrag: function(event) {
if (this.draggingSeekBar) {
this.seek(event);
}
this.$seekBarLoaded.removeClass('media-control-notransition');
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
this.draggingSeekBar = false;
this.draggingVolumeBar = false;
},
updateDrag: function(event) {
if (event) {
event.preventDefault();
}
if (this.draggingSeekBar) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.setSeekPercentage(pos);
} else if (this.draggingVolumeBar) {
this.volume(event);
}
},
volume: function(event) {
var offsetY = event.pageY - this.$volumeBarContainer.offset().top;
this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100;
this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0));
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
},
toggleMute: function() {
if (!!this.mute) {
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
this.mute = false;
} else {
this.container.setVolume(0);
this.setVolumeLevel(0);
this.mute = true;
}
},
toggleFullscreen: function() {
this.trigger('mediacontrol:fullscreen', this.name);
},
setContainer: function(container) {
this.stopListening(this.container);
this.container = container;
this.changeTogglePlay();
this.addEventListeners();
this.settingsUpdate();
this.container.setVolume(this.currentVolume);
if (this.container.mediaControlDisabled) {
this.disable();
}
this.trigger("mediacontrol:containerchanged");
},
showVolumeBar: function() {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.$volumeBarContainer.show();
this.$volumeBarContainer.removeClass('volume-bar-hide');
},
hideVolumeBar: function() {
var $__0 = this;
if (!this.$volumeBarContainer)
return;
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.hideVolumeId = setTimeout((function() {
$__0.$volumeBarContainer.one(transitionEvents, (function() {
$__0.$volumeBarContainer.off(transitionEvents);
$__0.$volumeBarContainer.hide();
}));
$__0.$volumeBarContainer.addClass('volume-bar-hide');
}), 750);
},
ended: function() {
this.changeTogglePlay();
},
updateProgressBar: function(startPosition, endPosition, duration) {
var loadedStart = startPosition / duration * 100;
var loadedEnd = endPosition / duration * 100;
this.$seekBarLoaded.css({
left: loadedStart + '%',
width: (loadedEnd - loadedStart) + '%'
});
},
updateSeekBar: function(position, duration) {
if (this.draggingSeekBar)
return;
if (position < 0)
position = duration;
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
var seekbarValue = (100 / duration) * position;
this.setSeekPercentage(seekbarValue);
this.$('[data-position]').html(Utils.formatTime(position));
this.$('[data-duration]').html(Utils.formatTime(duration));
},
seek: function(event) {
if (!this.container.settings.seekEnabled)
return;
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.container.setCurrentTime(pos);
},
setKeepVisible: function() {
this.keepVisible = true;
},
resetKeepVisible: function() {
this.keepVisible = false;
},
isVisible: function() {
return !this.$el.hasClass('media-control-hide');
},
show: function(event) {
var $__0 = this;
if (this.disabled || this.isVisible())
return;
var timeout = 2000;
if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {
if (this.hideId) {
clearTimeout(this.hideId);
}
this.$el.show();
this.trigger('mediacontrol:show', this.name);
this.$el.removeClass('media-control-hide');
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (event) {
this.lastMouseX = event.clientX;
this.lastMouseY = event.clientY;
}
}
},
hide: function() {
var $__0 = this;
var timeout = 2000;
if (this.hideId) {
clearTimeout(this.hideId);
}
if (!this.isVisible())
return;
if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) {
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
} else {
if (this.$volumeBarContainer) {
this.$volumeBarContainer.hide();
}
this.trigger('mediacontrol:hide', this.name);
this.$el.addClass('media-control-hide');
}
},
settingsUpdate: function() {
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.render();
},
highDefinitionUpdate: function() {
if (this.container.isHighDefinitionInUse()) {
this.$el.find('button[data-hd-indicator]').addClass("enabled");
} else {
this.$el.find('button[data-hd-indicator]').removeClass("enabled");
}
},
createCachedElements: function() {
this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');
this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');
this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');
this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');
this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');
this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');
this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');
this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');
this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]');
this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]');
this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]');
this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');
},
setVolumeLevel: function(value) {
var $__0 = this;
if (!this.container.isReady) {
this.listenToOnce(this.container, "container:ready", (function() {
return $__0.setVolumeLevel(value);
}));
} else {
var containerHeight = this.$volumeBarContainer.height();
var barHeight = this.$volumeBarBackground.height();
var offset = (containerHeight - barHeight) / 2.0;
var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset;
this.$volumeBarFill.css({height: value + '%'});
this.$volumeBarScrubber.css({bottom: pos});
if (value > 0) {
this.$volumeIcon.removeClass('muted');
} else {
this.$volumeIcon.addClass('muted');
}
}
},
setSeekPercentage: function(value) {
if (value > 100)
return;
var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);
this.currentSeekPercentage = value;
this.$seekBarPosition.css({width: value + '%'});
this.$seekBarScrubber.css({left: pos});
},
bindKeyEvents: function() {
var $__0 = this;
Mousetrap.bind(['space'], (function() {
return $__0.togglePlayPause();
}));
},
parseColors: function() {
var $__0 = this;
var translate = {
query: {
'seekbar': '.bar-fill-2[data-seekbar]',
'buttons': '[data-media-control] > .media-control-icon, [data-volume]'
},
rule: {
'seekbar': 'background-color',
'buttons': 'color'
}
};
var customColors = _.pick(this.options.mediacontrol, 'seekbar', 'buttons');
_.each(customColors, (function(value, key) {
$__0.$el.find(translate.query[key]).css(translate.rule[key], customColors[key]);
}));
},
render: function() {
var $__0 = this;
var timeout = 1000;
var style = Styler.getStyleFor('media_control');
this.$el.html(this.template({settings: this.settings}));
this.$el.append(style);
this.createCachedElements();
this.$playPauseToggle.addClass('paused');
this.$playStopToggle.addClass('stopped');
this.$volumeBarContainer.hide();
this.changeTogglePlay();
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (this.disabled) {
this.hide();
}
this.$seekBarHover.hide();
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (!this.currentSeekPercentage) {
this.currentSeekPercentage = 0;
}
this.setSeekPercentage(this.currentSeekPercentage);
this.$el.ready((function() {
if (!$__0.container.settings.seekEnabled) {
$__0.$seekBarContainer.addClass('seek-disabled');
}
$__0.setVolumeLevel($__0.currentVolume);
$__0.bindKeyEvents();
}));
this.parseColors();
this.seekTime.render();
return this;
}
}, {}, UIObject);
module.exports = MediaControl;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23,"../seek_time":44,"jquery":3,"mousetrap":4,"underscore":6}],"veeMMc":[function(require,module,exports){
"use strict";
var Events = require('../base/events');
var events = new Events();
var Mediator = function Mediator() {};
($traceurRuntime.createClass)(Mediator, {}, {});
Mediator.on = function(name, callback, context) {
events.on(name, callback, context);
return;
};
Mediator.once = function(name, callback, context) {
events.once(name, callback, context);
return;
};
Mediator.off = function(name, callback, context) {
events.off(name, callback, context);
return;
};
Mediator.trigger = function(name, opts) {
events.trigger(name, opts);
return;
};
Mediator.stopListening = function(obj, name, callback) {
events.stopListening(obj, name, callback);
return;
};
module.exports = Mediator;
},{"../base/events":13}],"mediator":[function(require,module,exports){
module.exports=require('veeMMc');
},{}],"Pce0iO":[function(require,module,exports){
"use strict";
module.exports = require('./player_info');
},{"./player_info":43}],"player_info":[function(require,module,exports){
module.exports=require('Pce0iO');
},{}],43:[function(require,module,exports){
"use strict";
var BaseObject = require('../../base/base_object');
var PlayerInfo = function PlayerInfo() {
this.options = {};
this.playbackPlugins = [];
this.currentSize = {
width: 0,
height: 0
};
};
($traceurRuntime.createClass)(PlayerInfo, {}, {}, BaseObject);
PlayerInfo.getInstance = function() {
if (this._instance === undefined) {
this._instance = new this();
}
return this._instance;
};
module.exports = PlayerInfo;
},{"../../base/base_object":"2HNVgz"}],44:[function(require,module,exports){
"use strict";
module.exports = require('./seek_time');
},{"./seek_time":45}],45:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var formatTime = require('../../base/utils').formatTime;
var SeekTime = function SeekTime(mediaControl) {
$traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []);
this.mediaControl = mediaControl;
this.addEventListeners();
};
var $SeekTime = SeekTime;
($traceurRuntime.createClass)(SeekTime, {
get name() {
return 'seek_time';
},
get template() {
return JST.seek_time;
},
get attributes() {
return {
'class': 'seek-time hidden',
'data-seek-time': ''
};
},
addEventListeners: function() {
this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime);
this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime);
},
showTime: function(event) {
var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left;
var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0));
var pointerPosition = offset - (this.$el.width() / 2);
var currentTime = timePosition * this.mediaControl.container.getDuration() / 100;
var options = {
timestamp: currentTime,
formattedTime: formatTime(currentTime),
pointerPosition: pointerPosition
};
this.update(options);
},
hideTime: function() {
this.$el.addClass('hidden');
},
update: function(options) {
if (this.mediaControl.container.getPlaybackType() === 'vod') {
this.$el.find('[data-seek-time]').text(options.formattedTime);
this.$el.css('left', options.pointerPosition);
this.$el.removeClass('hidden');
}
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.mediaControl.$el.append(this.el);
}
}, {}, UIObject);
module.exports = SeekTime;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23}],46:[function(require,module,exports){
(function (global){
"use strict";
var BaseObject = require('./base/base_object');
var CoreFactory = require('./components/core_factory');
var Loader = require('./components/loader');
var Mediator = require('./components/mediator');
var _ = require('underscore');
var ScrollMonitor = require('scrollmonitor');
var PlayerInfo = require('./components/player_info');
var Player = function Player(options) {
$traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]);
window.p = this;
this.options = options;
this.options.sources = this.normalizeSources(options);
this.loader = new Loader(this.options.plugins || []);
this.coreFactory = new CoreFactory(this, this.loader);
this.playerInfo = PlayerInfo.getInstance();
options.height || (options.height = 360);
options.width || (options.width = 640);
this.playerInfo.currentSize = {
width: options.width,
height: options.height
};
};
var $Player = Player;
($traceurRuntime.createClass)(Player, {
attachTo: function(element) {
this.options.parentElement = element;
this.core = this.coreFactory.create();
if (this.options.autoPlayVisible) {
this.bindAutoPlayVisible(this.options.autoPlayVisible);
}
},
bindAutoPlayVisible: function(option) {
var $__0 = this;
this.elementWatcher = ScrollMonitor.create(this.core.$el);
if (option === 'full') {
this.elementWatcher.fullyEnterViewport((function() {
return $__0.enterViewport();
}));
} else if (option === 'partial') {
this.elementWatcher.enterViewport((function() {
return $__0.enterViewport();
}));
}
},
enterViewport: function() {
if (this.elementWatcher.top !== 0 && !this.isPlaying()) {
this.play();
}
},
normalizeSources: function(options) {
return _.compact(_.flatten([options.source, options.sources]));
},
load: function(sources) {
this.core.load(sources);
},
destroy: function() {
this.core.destroy();
},
play: function() {
this.core.mediaControl.container.play();
},
pause: function() {
this.core.mediaControl.container.pause();
},
stop: function() {
this.core.mediaControl.container.stop();
},
seek: function(time) {
this.core.mediaControl.container.setCurrentTime(time);
},
setVolume: function(volume) {
this.core.mediaControl.container.setVolume(volume);
},
mute: function() {
this.core.mediaControl.container.setVolume(0);
},
unmute: function() {
this.core.mediaControl.container.setVolume(100);
},
isPlaying: function() {
return this.core.mediaControl.container.isPlaying();
}
}, {}, BaseObject);
global.DEBUG = false;
window.Clappr = {
Player: Player,
Mediator: Mediator
};
module.exports = window.Clappr;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./base/base_object":"2HNVgz","./components/core_factory":33,"./components/loader":34,"./components/mediator":"veeMMc","./components/player_info":"Pce0iO","scrollmonitor":5,"underscore":6}],47:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('../../components/mediator');
var _ = require('underscore');
var $ = require('jquery');
var Browser = require('../../components/browser');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var Flash = function Flash(options) {
$traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]);
this.src = options.src;
this.isRTMP = (this.src.indexOf("rtmp") > -1);
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf";
this.autoPlay = options.autoPlay;
this.settings = {default: ['seekbar']};
if (this.isRTMP) {
this.settings.left = ["playstop", "volume"];
this.settings.right = ["fullscreen"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["volume", "fullscreen"];
this.settings.seekEnabled = true;
}
this.isReady = false;
this.addListeners();
};
var $Flash = Flash;
($traceurRuntime.createClass)(Flash, {
get name() {
return 'flash';
},
get tagName() {
return 'object';
},
get template() {
return JST.flash;
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
if (this.currentState === 'PLAYING') {
this.firstPlay();
} else {
this.currentState = "IDLE";
this.autoPlay && this.play();
}
$('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el);
this.trigger('playback:ready', this.name);
},
getPlaybackType: function() {
return this.isRTMP ? 'live' : 'vod';
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-flash', '');
this.setElement($el[0]);
},
isHighDefinitionInUse: function() {
return false;
},
updateTime: function() {
this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name);
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':progress', (function() {
return $__0.progress();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':statechanged', (function() {
return $__0.checkState();
}));
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':progress');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':statechanged');
},
checkState: function() {
if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") {
this.trigger('playback:buffering', this.name);
this.currentState = "PLAYING_BUFFERING";
} else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") {
this.trigger('playback:bufferfull', this.name);
this.currentState = "PLAYING";
} else if (this.el.getState() === "IDLE") {
this.currentState = "IDLE";
} else if (this.el.getState() === "ENDED") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name);
this.currentState = "ENDED";
}
},
progress: function() {
if (this.currentState !== "IDLE" && this.currentState !== "ENDED") {
this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);
}
},
firstPlay: function() {
this.currentState = "PLAYING";
if (_.isFunction(this.el.playerPlay)) {
this.el.playerPlay(this.src);
}
},
play: function() {
if (this.el.getState() === 'PAUSED') {
this.currentState = "PLAYING";
this.el.playerResume();
} else if (this.el.getState() !== 'PLAYING') {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.playerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
this.currentState = "PAUSED";
this.el.playerPause();
},
stop: function() {
this.el.playerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
return !!(this.isReady && this.currentState === "PLAYING");
},
getDuration: function() {
return this.el.getDuration();
},
seek: function(time) {
var seekTo = this.el.getDuration() * (time / 100);
this.el.playerSeek(seekTo);
this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name);
if (this.currentState === "PAUSED") {
this.pause();
}
},
destroy: function() {
clearInterval(this.bootstrapId);
this.stopListening();
this.$el.remove();
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isLegacyIE) {
this.setupIE();
}
this.$el.append(style);
return this;
}
}, {}, UIObject);
Flash.canPlay = function(resource) {
if (resource.indexOf('rtmp') > -1) {
return true;
} else if (Browser.isFirefox || Browser.isLegacyIE) {
return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/);
} else {
return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/);
}
};
module.exports = Flash;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../components/browser":"195Wj5","../../components/mediator":"veeMMc","jquery":3,"underscore":6}],48:[function(require,module,exports){
"use strict";
module.exports = require('./flash');
},{"./flash":47}],49:[function(require,module,exports){
"use strict";
var Playback = require('../../base/playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var _ = require("underscore");
var Mediator = require('../../components/mediator');
var Browser = require('../../components/browser');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var HLS = function HLS(options) {
$traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]);
this.src = options.src;
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf";
this.highDefinition = false;
this.autoPlay = options.autoPlay;
this.defaultSettings = {
left: ["playstop"],
default: ['seekbar'],
right: ["fullscreen", "volume", "hd-indicator"],
seekEnabled: true
};
this.settings = _.extend({}, this.defaultSettings);
this.addListeners();
};
var $HLS = HLS;
($traceurRuntime.createClass)(HLS, {
get name() {
return 'hls';
},
get tagName() {
return 'object';
},
get template() {
return JST.hls;
},
get attributes() {
return {
'class': 'hls-playback',
'data-hls': '',
'type': 'application/x-shockwave-flash'
};
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':playbackstate', (function(state) {
return $__0.setPlaybackState(state);
}));
Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {
return $__0.updateHighDefinition(isHD);
}));
Mediator.on(this.uniqueId + ':playbackerror', (function() {
return $__0.flashPlaybackError();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':flashready');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':playbackstate');
Mediator.off(this.uniqueId + ':highdefinition');
Mediator.off(this.uniqueId + ':playbackerror');
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger('playback:ready', this.name);
this.currentState = "IDLE";
this.el.globoPlayerSetflushLiveURLCache(true);
this.autoPlay && this.play();
},
updateHighDefinition: function(isHD) {
this.highDefinition = (isHD === "true");
this.trigger('playback:highdefinitionupdate');
},
updateTime: function() {
var duration = this.getDuration();
var position = this.el.globoGetPosition();
var livePlayback = this.playbackType === 'live';
if (livePlayback && (position >= duration || position < 0)) {
position = duration;
}
var previousDVRStatus = this.dvrEnabled;
this.dvrEnabled = (livePlayback && duration > 240);
if (this.dvrEnabled !== previousDVRStatus) {
this.updateSettings();
this.trigger('playback:settingsupdate', this.name);
}
if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {
position = duration;
}
this.trigger('playback:timeupdate', position, duration, this.name);
},
play: function() {
if (this.currentState === 'PAUSED') {
this.el.globoPlayerResume();
} else if (this.currentState !== "PLAYING") {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
getPlaybackType: function() {
if (this.playbackType)
return this.playbackType;
return null;
},
getCurrentBitrate: function() {
var currentLevel = this.getLevels()[this.el.globoGetLevel()];
return currentLevel.bitrate;
},
getLastProgramDate: function() {
var programDate = this.el.globoGetLastProgramDate();
return programDate - 1.08e+7;
},
isHighDefinitionInUse: function() {
return this.highDefinition;
},
getLevels: function() {
if (!this.levels || this.levels.length === 0) {
this.levels = this.el.globoGetLevels();
}
return this.levels;
},
setPlaybackState: function(state) {
var bufferLength = this.el.globoGetbufferLength();
if (state === "PLAYING_BUFFERING" && bufferLength < 1) {
this.trigger('playback:buffering', this.name);
this.updateCurrentState(state);
} else if (state === "PLAYING") {
if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) {
this.trigger('playback:bufferfull', this.name);
this.updateCurrentState(state);
}
} else if (state === "PAUSED") {
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name);
this.updateCurrentState(state);
}
this.lastBufferLength = bufferLength;
},
updateCurrentState: function(state) {
this.currentState = state;
this.updatePlaybackType();
},
updatePlaybackType: function() {
this.playbackType = this.el.globoGetType();
if (this.playbackType) {
this.playbackType = this.playbackType.toLowerCase();
}
this.trigger('playback:playbackstate');
},
firstPlay: function() {
this.el.globoPlayerLoad(this.src);
this.el.globoPlayerPlay();
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.globoPlayerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
if (this.playbackType !== 'live' || this.dvrEnabled) {
this.el.globoPlayerPause();
if (this.playbackType === 'live' && this.dvrEnabled) {
this.updateDvr(true);
}
}
},
stop: function() {
this.el.globoPlayerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
if (this.currentState) {
return !!(this.currentState.match(/playing/i));
}
return false;
},
getDuration: function() {
var duration = this.el.globoGetDuration();
if (this.playbackType === 'live') {
duration = duration - 10;
}
return duration;
},
seek: function(time) {
var duration = this.getDuration();
if (time > 0) {
time = duration * time / 100;
}
if (this.playbackType === 'live') {
var dvrInUse = (time >= 0 && duration - time > 5);
if (!dvrInUse) {
time = -1;
}
this.updateDvr(dvrInUse);
}
this.el.globoPlayerSeek(time);
this.trigger('playback:timeupdate', time, duration, this.name);
},
updateDvr: function(dvrInUse) {
var previousDvrInUse = !!this.dvrInUse;
this.dvrInUse = dvrInUse;
if (this.dvrInUse !== previousDvrInUse) {
this.updateSettings();
this.trigger('playback:dvr', this.dvrInUse);
this.trigger('playback:stats:add', {'dvr': this.dvrInUse});
}
},
flashPlaybackError: function() {
this.trigger('playback:stop');
},
timeUpdate: function(time, duration) {
this.trigger('playback:timeupdate', time, duration, this.name);
},
destroy: function() {
this.stopListening();
this.$el.remove();
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-hls', '');
this.setElement($el);
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
updateSettings: function() {
this.settings = _.extend({}, this.defaultSettings);
if (this.playbackType === "vod" || this.dvrInUse) {
this.settings.left = ["playpause", "position", "duration"];
} else if (this.dvrEnabled) {
this.settings.left = ["playpause"];
} else {
this.settings.seekEnabled = false;
}
},
setElement: function(element) {
this.$el = element;
this.el = element[0];
},
render: function() {
var style = Styler.getStyleFor(this.name);
if (Browser.isLegacyIE) {
this.setupIE();
} else {
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isIE) {
this.$('embed').remove();
}
}
this.el.id = this.cid;
this.$el.append(style);
return this;
}
}, {}, Playback);
HLS.canPlay = function(resource) {
return !!resource.match(/^http(.*).m3u8/);
};
module.exports = HLS;
},{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","../../components/mediator":"veeMMc","underscore":6}],50:[function(require,module,exports){
"use strict";
module.exports = require('./hls');
},{"./hls":49}],51:[function(require,module,exports){
"use strict";
var Playback = require('../../base/playback');
var HTML5Audio = function HTML5Audio(params) {
$traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]);
this.el.src = params.src;
this.settings = {
left: ['playpause', 'position', 'duration'],
right: ['fullscreen', 'volume'],
default: ['seekbar']
};
this.render();
params.autoPlay && this.play();
};
var $HTML5Audio = HTML5Audio;
($traceurRuntime.createClass)(HTML5Audio, {
get name() {
return 'html5_audio';
},
get tagName() {
return 'audio';
},
get events() {
return {
'timeupdate': 'timeUpdated',
'ended': 'ended'
};
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.play);
this.listenTo(this.container, 'container:pause', this.pause);
this.listenTo(this.container, 'container:seek', this.seek);
this.listenTo(this.container, 'container:volume', this.volume);
this.listenTo(this.container, 'container:stop', this.stop);
},
getPlaybackType: function() {
return "aod";
},
play: function() {
this.el.play();
this.trigger('playback:play');
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger('container:timeupdate', 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
timeUpdated: function() {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
},
render: function() {
return this;
}
}, {}, Playback);
HTML5Audio.canPlay = function(resource) {
return !!resource.match(/(.*).mp3/);
};
module.exports = HTML5Audio;
},{"../../base/playback":"VbgHr3"}],52:[function(require,module,exports){
"use strict";
module.exports = require('./html5_audio');
},{"./html5_audio":51}],53:[function(require,module,exports){
"use strict";
var Playback = require('../../base/playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('../../components/browser');
var _ = require('underscore');
var HTML5Video = function HTML5Video(options) {
$traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]);
this.options = options;
this.src = options.src;
this.el.src = options.src;
this.el.loop = options.loop;
this.isHLS = (this.src.indexOf('m3u8') > -1);
this.settings = {default: ['seekbar']};
if (this.isHLS) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
};
var $HTML5Video = HTML5Video;
($traceurRuntime.createClass)(HTML5Video, {
get name() {
return 'html5_video';
},
get tagName() {
return 'video';
},
get template() {
return JST.html5_video;
},
get attributes() {
return {'data-html5-video': ''};
},
get events() {
return {
'timeupdate': 'timeUpdated',
'progress': 'progress',
'ended': 'ended',
'playing': 'playing',
'stalled': 'stalled',
'waiting': 'waiting',
'canplaythrough': 'bufferFull',
'loadedmetadata': 'loadedMetadata'
};
},
loadedMetadata: function(e) {
this.trigger('playback:loadedmetadata', e.target.duration);
this.trigger('playback:settingsupdate');
},
getPlaybackType: function() {
return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod';
},
isHighDefinitionInUse: function() {
return false;
},
play: function() {
this.el.play();
this.trigger('playback:play');
if (this.isHLS) {
this.trigger('playback:timeupdate', 1, 1, this.name);
}
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
if (this.el.readyState !== 0) {
this.el.currentTime = 0;
}
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
ended: function() {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.duration, this.name);
},
stalled: function() {
if (this.getPlaybackType() === 'vod') {
this.trigger('playback:buffering', this.name);
}
},
waiting: function() {
this.trigger('playback:buffering', this.name);
},
bufferFull: function() {
this.trigger('playback:bufferfull', this.name);
},
destroy: function() {
this.stop();
this.el.src = '';
this.$el.remove();
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
if (this.getPlaybackType() !== 'live') {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
}
},
progress: function() {
if (!this.el.buffered.length)
return;
var bufferedPos = 0;
for (var i = 0; i < this.el.buffered.length; i++) {
if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
bufferedPos = i;
break;
}
}
this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
},
typeFor: function(src) {
return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
src: this.src,
type: this.typeFor(this.src)
}));
this.$el.append(style);
this.trigger('playback:ready', this.name);
this.options.autoPlay && this.play();
return this;
}
}, {}, Playback);
HTML5Video.canPlay = function(resource) {
return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App);
};
module.exports = HTML5Video;
},{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","underscore":6}],54:[function(require,module,exports){
"use strict";
module.exports = require('./html5_video');
},{"./html5_video":53}],55:[function(require,module,exports){
"use strict";
module.exports = require('./no_op');
},{"./no_op":56}],56:[function(require,module,exports){
"use strict";
var Playback = require('../../base/playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var NoOp = function NoOp(options) {
$traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]);
};
var $NoOp = NoOp;
($traceurRuntime.createClass)(NoOp, {
get name() {
return 'no_op';
},
get template() {
return JST.no_op;
},
get attributes() {
return {'data-no-op': ''};
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
return this;
}
}, {}, Playback);
NoOp.canPlay = (function(source) {
return true;
});
module.exports = NoOp;
},{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17}],57:[function(require,module,exports){
"use strict";
var UICorePlugin = require('../../base/ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var BackgroundButton = function BackgroundButton(core) {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $BackgroundButton = BackgroundButton;
($traceurRuntime.createClass)(BackgroundButton, {
get template() {
return JST.background_button;
},
get name() {
return 'background_button';
},
get events() {
return {'click .playpause-icon': 'click'};
},
get attributes() {
return {
'class': 'background-button',
'data-background-button': ''
};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide);
this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show);
this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.show);
this.listenTo(this.core.mediaControl, 'mediacontrol:hide', this.hide);
this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing);
this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying);
},
settingsUpdate: function() {
this.stopListening();
if (this.shouldRender()) {
this.render();
this.bindEvents();
if (this.core.mediaControl.container.isPlaying()) {
this.playing();
} else {
this.notplaying();
}
} else {
this.hide();
this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate);
}
},
shouldRender: function() {
var settings = this.core.mediaControl.settings;
var useBackgroundButton = this.core.options.useBackgroundButton === undefined || !!this.core.options.useBackgroundButton;
return useBackgroundButton && (settings.default.indexOf('playpause') >= 0 || settings.left.indexOf('playpause') >= 0 || settings.right.indexOf('playpause') >= 0);
},
click: function() {
this.core.mediaControl.togglePlayPause();
},
show: function() {
this.$el.removeClass('hide');
},
hide: function() {
this.$el.addClass('hide');
},
enable: function() {
this.stopListening();
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []);
this.core.mediaControl.$el.find('[data-playpause]').hide();
},
disable: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []);
this.core.mediaControl.$el.find('[data-playpause]').show();
},
playing: function() {
this.$el.find('.playpause-icon[data-background-button]').removeClass('paused').addClass('playing');
},
notplaying: function() {
this.$el.find('.playpause-icon[data-background-button]').removeClass('playing').addClass('paused');
},
getExternalInterface: function() {},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
if (this.enabled) {
this.core.mediaControl.$el.find('[data-playpause]').hide();
}
this.core.$el.append(this.$el);
if (this.core.mediaControl.isVisible()) {
this.show();
}
return this;
}
}, {}, UICorePlugin);
module.exports = BackgroundButton;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_core_plugin":"gNZMEo"}],58:[function(require,module,exports){
"use strict";
module.exports = require('./background_button');
},{"./background_button":57}],59:[function(require,module,exports){
"use strict";
module.exports = require('./log');
},{"./log":60}],60:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var BOLD = 'font-weight: bold; font-size: 13px;';
var INFO = 'color: green;' + BOLD;
var DEBUG = 'color: #222;' + BOLD;
var ERROR = 'color: red;' + BOLD;
var DEFAULT = '';
$(document).keydown(function(e) {
if (e.ctrlKey && e.shiftKey && e.keyCode === 68) {
window.DEBUG = !window.DEBUG;
}
});
var Log = function(klass) {
this.klass = klass || 'Logger';
};
Log.info = function(klass, msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg);
};
Log.error = function(klass, msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg);
};
Log.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
Log.prototype = {
log: function(msg) {
this.info(msg);
},
info: function(msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg);
},
error: function(msg) {
console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg);
}
};
module.exports = Log;
},{"jquery":3}],61:[function(require,module,exports){
"use strict";
module.exports = require('./poster');
},{"./poster":62}],62:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('../../base/ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('../../components/mediator');
var PlayerInfo = require('../../components/player_info');
var $ = require('jquery');
var _ = require('underscore');
var PosterPlugin = function PosterPlugin(options) {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]);
this.options = options;
_.defaults(this.options, {disableControlsOnPoster: true});
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
this.render();
};
var $PosterPlugin = PosterPlugin;
($traceurRuntime.createClass)(PosterPlugin, {
get name() {
return 'poster';
},
get template() {
return JST.poster;
},
get attributes() {
return {
'class': 'player-poster',
'data-poster': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
var $__0 = this;
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:ended', this.onStop);
Mediator.on('player:resize', (function() {
return $__0.updateSize();
}));
},
onBuffering: function() {
this.hidePlayButton();
},
onPlay: function() {
this.$el.hide();
if (this.options.disableControlsOnPoster) {
this.container.enableMediaControl();
}
},
onStop: function() {
this.$el.show();
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
if (!this.options.hidePlayButton) {
this.showPlayButton();
}
},
hidePlayButton: function() {
this.$playButton.hide();
},
showPlayButton: function() {
this.updateSize();
this.$playButton.show();
},
clicked: function() {
this.container.play();
},
updateSize: function() {
if (!this.$el)
return;
var playerInfo = PlayerInfo.getInstance();
var height = playerInfo.currentSize ? playerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.container.$el.append(this.el);
this.$el.ready((function() {
return $__0.updateSize();
}));
this.$playButton = $(this.$el.find('.play-wrapper'));
if (this.options.poster !== undefined) {
var imgEl = $('<img data-poster class="poster-background"></img>');
imgEl.attr('src', this.options.poster);
this.$el.prepend(imgEl);
}
return this;
}
}, {}, UIContainerPlugin);
module.exports = PosterPlugin;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT","../../components/mediator":"veeMMc","../../components/player_info":"Pce0iO","jquery":3,"underscore":6}],63:[function(require,module,exports){
"use strict";
module.exports = require('./spinner_three_bounce');
},{"./spinner_three_bounce":64}],64:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('../../base/ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {
$traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]);
this.template = JST.spinner_three_bounce;
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stop', this.onStop);
this.render();
};
var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;
($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {
get name() {
return 'spinner';
},
get attributes() {
return {
'data-spinner': '',
'class': 'spinner-three-bounce'
};
},
onBuffering: function() {
this.$el.show();
},
onBufferFull: function() {
this.$el.hide();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.html(this.template());
var style = Styler.getStyleFor('spinner_three_bounce');
this.container.$el.append(style);
this.container.$el.append(this.$el);
this.$el.hide();
return this;
}
}, {}, UIContainerPlugin);
module.exports = SpinnerThreeBouncePlugin;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}],65:[function(require,module,exports){
"use strict";
module.exports = require('./stats');
},{"./stats":66}],66:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('../../base/container_plugin');
var $ = require("jquery");
var StatsPlugin = function StatsPlugin(options) {
$traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]);
this.setInitialAttrs();
this.reportInterval = options.reportInterval || 5000;
this.state = "IDLE";
};
var $StatsPlugin = StatsPlugin;
($traceurRuntime.createClass)(StatsPlugin, {
get name() {
return 'stats';
},
bindEvents: function() {
this.listenTo(this.container.playback, 'playback:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:destroyed', this.onStop);
this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval);
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stats:add', this.onStatsAdd);
this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd);
},
setReportInterval: function(reportInterval) {
this.reportInterval = reportInterval;
},
setInitialAttrs: function() {
this.firstPlay = true;
this.startupTime = 0;
this.rebufferingTime = 0;
this.watchingTime = 0;
this.rebuffers = 0;
this.externalMetrics = {};
},
onPlay: function() {
this.state = "PLAYING";
this.watchingTimeInit = Date.now();
if (!this.intervalId) {
this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
}
},
onStop: function() {
clearInterval(this.intervalId);
this.intervalId = undefined;
this.state = "STOPPED";
},
onBuffering: function() {
if (this.firstPlay) {
this.startupTimeInit = Date.now();
} else {
this.rebufferingTimeInit = Date.now();
}
this.state = "BUFFERING";
this.rebuffers++;
},
onBufferFull: function() {
if (this.firstPlay) {
this.firstPlay = false;
this.startupTime = Date.now() - this.startupTimeInit;
this.watchingTimeInit = Date.now();
} else if (!!this.rebufferingTimeInit) {
this.rebufferingTime += this.getRebufferingTime();
}
this.rebufferingTimeInit = undefined;
this.state = "PLAYING";
},
getRebufferingTime: function() {
return Date.now() - this.rebufferingTimeInit;
},
getWatchingTime: function() {
var totalTime = (Date.now() - this.watchingTimeInit);
return totalTime - this.rebufferingTime;
},
isRebuffering: function() {
return !!this.rebufferingTimeInit;
},
onStatsAdd: function(metric) {
$.extend(this.externalMetrics, metric);
},
getStats: function() {
var metrics = {
startupTime: this.startupTime,
rebuffers: this.rebuffers,
rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,
watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()
};
$.extend(metrics, this.externalMetrics);
return metrics;
},
report: function() {
var stats = this.getStats();
this.container.statsReport(this.getStats());
}
}, {}, ContainerPlugin);
module.exports = StatsPlugin;
},{"../../base/container_plugin":"6xH8xW","jquery":3}],67:[function(require,module,exports){
"use strict";
module.exports = require('./watermark');
},{"./watermark":68}],68:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('../../base/ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var WaterMarkPlugin = function WaterMarkPlugin(options) {
$traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.position = options.position || "bottom-right";
if (options.watermark) {
this.imageUrl = options.watermark;
this.render();
} else {
this.$el.remove();
}
};
var $WaterMarkPlugin = WaterMarkPlugin;
($traceurRuntime.createClass)(WaterMarkPlugin, {
get name() {
return 'watermark';
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
},
onPlay: function() {
if (!this.hidden)
this.$el.show();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
var templateOptions = {
position: this.position,
imageUrl: this.imageUrl
};
this.$el.html(this.template(templateOptions));
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIContainerPlugin);
module.exports = WaterMarkPlugin;
},{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}]},{},[2,46]) |
www/src/containers/survey/SurveyUserListContainer.js | cygwin255/SimpleSurvey | import React from 'react'
import * as actions from 'actions'
import { connect } from 'react-redux'
import {
surveysCollectionSelector,
surveysCurrentPageSelector,
surveysTotalPagesSelector,
surveysTotalSurveysSelector
} from 'reducers/surveyReducer/SurveysReducer'
import SurveyUserList from 'components/survey/SurveyUserList'
class SurveyUserListContainer extends React.Component {
componentWillMount () {
let { fetchSurveys, page } = this.props
fetchSurveys(page)
}
render () {
let { fetchSurveys, ...props } = this.props
return (
<SurveyUserList
{...props}
update={fetchSurveys}
/>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
surveys: surveysCollectionSelector(state),
page: surveysCurrentPageSelector(state),
pages: surveysTotalPagesSelector(state),
total: surveysTotalSurveysSelector(state)
}
}
const SurveyUserListContainerConnector = connect(
mapStateToProps,
actions,
null,
{ pure: false }
)(SurveyUserListContainer)
export default SurveyUserListContainerConnector
|
app/javascript/mastodon/features/compose/components/navigation_bar.js | narabo/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Avatar from '../../../components/avatar';
import IconButton from '../../../components/icon_button';
import DisplayName from '../../../components/display_name';
import Permalink from '../../../components/permalink';
import { FormattedMessage } from 'react-intl';
import Link from 'react-router/lib/Link';
import ImmutablePureComponent from 'react-immutable-pure-component';
class NavigationBar extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
};
render () {
return (
<div className='navigation-bar'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<Avatar src={this.props.account.get('avatar')} animate size={40} />
</Permalink>
<div className='navigation-bar__profile'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<strong className='navigation-bar__profile-account'>@{this.props.account.get('acct')}</strong>
</Permalink>
<a href='/settings/profile' className='navigation-bar__profile-edit'><FormattedMessage id='navigation_bar.edit_profile' defaultMessage='Edit profile' /></a>
</div>
</div>
);
}
}
export default NavigationBar;
|
docs/app/Examples/modules/Progress/Variations/Color.js | jamiehill/stardust | import React from 'react'
import { Progress } from 'stardust'
const ProgressColorExample = () => (
<div>
<Progress percent={32} color='red' />
<Progress percent={59} color='orange' />
<Progress percent={13} color='yellow' />
<Progress percent={37} color='olive' />
<Progress percent={83} color='green' />
<Progress percent={23} color='teal' />
<Progress percent={85} color='blue' />
<Progress percent={38} color='violet' />
<Progress percent={47} color='purple' />
<Progress percent={29} color='pink' />
<Progress percent={68} color='brown' />
<Progress percent={36} color='grey' />
<Progress percent={72} color='black' />
</div>
)
export default ProgressColorExample
|
src/svg-icons/action/info-outline.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInfoOutline = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/>
</SvgIcon>
);
ActionInfoOutline = pure(ActionInfoOutline);
ActionInfoOutline.displayName = 'ActionInfoOutline';
export default ActionInfoOutline;
|
src/components/trello/plain-wordmark/TrelloPlainWordmark.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './TrelloPlainWordmark.svg'
/** TrelloPlainWordmark */
function TrelloPlainWordmark({ width, height, className }) {
return (
<SVGDeviconInline
className={'TrelloPlainWordmark' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
TrelloPlainWordmark.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default TrelloPlainWordmark
|
src/collections/Table/TableFooter.js | shengnian/shengnian-ui-react | import React from 'react'
import {
customPropTypes,
getUnhandledProps,
META,
} from '../../lib'
import TableHeader from './TableHeader'
/**
* A table can have a footer.
*/
function TableFooter(props) {
const { as } = props
const rest = getUnhandledProps(TableFooter, props)
return <TableHeader {...rest} as={as} />
}
TableFooter._meta = {
name: 'TableFooter',
type: META.TYPES.COLLECTION,
parent: 'Table',
}
TableFooter.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
}
TableFooter.defaultProps = {
as: 'tfoot',
}
export default TableFooter
|
ajax/libs/yui/3.17.1/datatable-core/datatable-core.js | schoren/cdnjs | /*
YUI 3.17.1 (build 0eb5a52)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('datatable-core', function (Y, NAME) {
/**
The core implementation of the `DataTable` and `DataTable.Base` Widgets.
@module datatable
@submodule datatable-core
@since 3.5.0
**/
var INVALID = Y.Attribute.INVALID_VALUE,
Lang = Y.Lang,
isFunction = Lang.isFunction,
isObject = Lang.isObject,
isArray = Lang.isArray,
isString = Lang.isString,
isNumber = Lang.isNumber,
toArray = Y.Array,
keys = Y.Object.keys,
Table;
/**
_API docs for this extension are included in the DataTable class._
Class extension providing the core API and structure for the DataTable Widget.
Use this class extension with Widget or another Base-based superclass to create
the basic DataTable model API and composing class structure.
@class DataTable.Core
@for DataTable
@since 3.5.0
**/
Table = Y.namespace('DataTable').Core = function () {};
Table.ATTRS = {
/**
Columns to include in the rendered table.
If omitted, the attributes on the configured `recordType` or the first item
in the `data` collection will be used as a source.
This attribute takes an array of strings or objects (mixing the two is
fine). Each string or object is considered a column to be rendered.
Strings are converted to objects, so `columns: ['first', 'last']` becomes
`columns: [{ key: 'first' }, { key: 'last' }]`.
DataTable.Core only concerns itself with a few properties of columns.
These properties are:
* `key` - Used to identify the record field/attribute containing content for
this column. Also used to create a default Model if no `recordType` or
`data` are provided during construction. If `name` is not specified, this
is assigned to the `_id` property (with added incrementer if the key is
used by multiple columns).
* `children` - Traversed to initialize nested column objects
* `name` - Used in place of, or in addition to, the `key`. Useful for
columns that aren't bound to a field/attribute in the record data. This
is assigned to the `_id` property.
* `id` - For backward compatibility. Implementers can specify the id of
the header cell. This should be avoided, if possible, to avoid the
potential for creating DOM elements with duplicate IDs.
* `field` - For backward compatibility. Implementers should use `name`.
* `_id` - Assigned unique-within-this-instance id for a column. By order
of preference, assumes the value of `name`, `key`, `id`, or `_yuid`.
This is used by the rendering views as well as feature module
as a means to identify a specific column without ambiguity (such as
multiple columns using the same `key`.
* `_yuid` - Guid stamp assigned to the column object.
* `_parent` - Assigned to all child columns, referencing their parent
column.
@attribute columns
@type {Object[]|String[]}
@default (from `recordType` ATTRS or first item in the `data`)
@since 3.5.0
**/
columns: {
// TODO: change to setter to clone input array/objects
validator: isArray,
setter: '_setColumns',
getter: '_getColumns'
},
/**
Model subclass to use as the `model` for the ModelList stored in the `data`
attribute.
If not provided, it will try really hard to figure out what to use. The
following attempts will be made to set a default value:
1. If the `data` attribute is set with a ModelList instance and its `model`
property is set, that will be used.
2. If the `data` attribute is set with a ModelList instance, and its
`model` property is unset, but it is populated, the `ATTRS` of the
`constructor of the first item will be used.
3. If the `data` attribute is set with a non-empty array, a Model subclass
will be generated using the keys of the first item as its `ATTRS` (see
the `_createRecordClass` method).
4. If the `columns` attribute is set, a Model subclass will be generated
using the columns defined with a `key`. This is least desirable because
columns can be duplicated or nested in a way that's not parsable.
5. If neither `data` nor `columns` is set or populated, a change event
subscriber will listen for the first to be changed and try all over
again.
@attribute recordType
@type {Function}
@default (see description)
@since 3.5.0
**/
recordType: {
getter: '_getRecordType',
setter: '_setRecordType'
},
/**
The collection of data records to display. This attribute is a pass
through to a `data` property, which is a ModelList instance.
If this attribute is passed a ModelList or subclass, it will be assigned to
the property directly. If an array of objects is passed, a new ModelList
will be created using the configured `recordType` as its `model` property
and seeded with the array.
Retrieving this attribute will return the ModelList stored in the `data`
property.
@attribute data
@type {ModelList|Object[]}
@default `new ModelList()`
@since 3.5.0
**/
data: {
valueFn: '_initData',
setter : '_setData',
lazyAdd: false
},
/**
Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned
to this attribute will be HTML escaped for security.
@attribute summary
@type {String}
@default '' (empty string)
@since 3.5.0
**/
//summary: {},
/**
HTML content of an optional `<caption>` element to appear above the table.
Leave this config unset or set to a falsy value to remove the caption.
@attribute caption
@type HTML
@default '' (empty string)
@since 3.5.0
**/
//caption: {},
/**
Deprecated as of 3.5.0. Passes through to the `data` attribute.
WARNING: `get('recordset')` will NOT return a Recordset instance as of
3.5.0. This is a break in backward compatibility.
@attribute recordset
@type {Object[]|Recordset}
@deprecated Use the `data` attribute
@since 3.5.0
**/
recordset: {
setter: '_setRecordset',
getter: '_getRecordset',
lazyAdd: false
},
/**
Deprecated as of 3.5.0. Passes through to the `columns` attribute.
WARNING: `get('columnset')` will NOT return a Columnset instance as of
3.5.0. This is a break in backward compatibility.
@attribute columnset
@type {Object[]}
@deprecated Use the `columns` attribute
@since 3.5.0
**/
columnset: {
setter: '_setColumnset',
getter: '_getColumnset',
lazyAdd: false
}
};
Y.mix(Table.prototype, {
// -- Instance properties -------------------------------------------------
/**
The ModelList that manages the table's data.
@property data
@type {ModelList}
@default undefined (initially unset)
@since 3.5.0
**/
//data: null,
// -- Public methods ------------------------------------------------------
/**
Gets the column configuration object for the given key, name, or index. For
nested columns, `name` can be an array of indexes, each identifying the index
of that column in the respective parent's "children" array.
If you pass a column object, it will be returned.
For columns with keys, you can also fetch the column with
`instance.get('columns.foo')`.
@method getColumn
@param {String|Number|Number[]} name Key, "name", index, or index array to
identify the column
@return {Object} the column configuration object
@since 3.5.0
**/
getColumn: function (name) {
var col, columns, i, len, cols;
if (isObject(name) && !isArray(name)) {
if (name && name._node) {
col = this.body.getColumn(name);
} else {
col = name;
}
} else {
col = this.get('columns.' + name);
}
if (col) {
return col;
}
columns = this.get('columns');
if (isNumber(name) || isArray(name)) {
name = toArray(name);
cols = columns;
for (i = 0, len = name.length - 1; cols && i < len; ++i) {
cols = cols[name[i]] && cols[name[i]].children;
}
return (cols && cols[name[i]]) || null;
}
return null;
},
/**
Returns the Model associated to the record `id`, `clientId`, or index (not
row index). If none of those yield a Model from the `data` ModelList, the
arguments will be passed to the `view` instance's `getRecord` method
if it has one.
If no Model can be found, `null` is returned.
@method getRecord
@param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or
identifier for a row or child element
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var record = this.data.getById(seed) || this.data.getByClientId(seed);
if (!record) {
if (isNumber(seed)) {
record = this.data.item(seed);
}
// TODO: this should be split out to base somehow
if (!record && this.view && this.view.getRecord) {
record = this.view.getRecord.apply(this.view, arguments);
}
}
return record || null;
},
// -- Protected and private properties and methods ------------------------
/**
This tells `Y.Base` that it should create ad-hoc attributes for config
properties passed to DataTable's constructor. This is useful for setting
configurations on the DataTable that are intended for the rendering View(s).
@property _allowAdHocAttrs
@type Boolean
@default true
@protected
@since 3.6.0
**/
_allowAdHocAttrs: true,
/**
A map of column key to column configuration objects parsed from the
`columns` attribute.
@property _columnMap
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_columnMap: null,
/**
The Node instance of the table containing the data rows. This is set when
the table is rendered. It may also be set by progressive enhancement,
though this extension does not provide the logic to parse from source.
@property _tableNode
@type {Node}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_tableNode: null,
/**
Updates the `_columnMap` property in response to changes in the `columns`
attribute.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
_afterColumnsChange: function (e) {
this._setColumnMap(e.newVal);
},
/**
Updates the `modelList` attributes of the rendered views in response to the
`data` attribute being assigned a new ModelList.
@method _afterDataChange
@param {EventFacade} e the `dataChange` event
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var modelList = e.newVal;
this.data = e.newVal;
if (!this.get('columns') && modelList.size()) {
// TODO: this will cause a re-render twice because the Views are
// subscribed to columnsChange
this._initColumns();
}
},
/**
Assigns to the new recordType as the model for the data ModelList
@method _afterRecordTypeChange
@param {EventFacade} e recordTypeChange event
@protected
@since 3.6.0
**/
_afterRecordTypeChange: function (e) {
var data = this.data.toJSON();
this.data.model = e.newVal;
this.data.reset(data);
if (!this.get('columns') && data) {
if (data.length) {
this._initColumns();
} else {
this.set('columns', keys(e.newVal.ATTRS));
}
}
},
/**
Creates a Model subclass from an array of attribute names or an object of
attribute definitions. This is used to generate a class suitable to
represent the data passed to the `data` attribute if no `recordType` is
set.
@method _createRecordClass
@param {String[]|Object} attrs Names assigned to the Model subclass's
`ATTRS` or its entire `ATTRS` definition object
@return {Model}
@protected
@since 3.5.0
**/
_createRecordClass: function (attrs) {
var ATTRS, i, len;
if (isArray(attrs)) {
ATTRS = {};
for (i = 0, len = attrs.length; i < len; ++i) {
ATTRS[attrs[i]] = {};
}
} else if (isObject(attrs)) {
ATTRS = attrs;
}
return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });
},
/**
Tears down the instance.
@method destructor
@protected
@since 3.6.0
**/
destructor: function () {
new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();
},
/**
The getter for the `columns` attribute. Returns the array of column
configuration objects if `instance.get('columns')` is called, or the
specific column object if `instance.get('columns.columnKey')` is called.
@method _getColumns
@param {Object[]} columns The full array of column objects
@param {String} name The attribute name requested
(e.g. 'columns' or 'columns.foo');
@protected
@since 3.5.0
**/
_getColumns: function (columns, name) {
// Workaround for an attribute oddity (ticket #2529254)
// getter is expected to return an object if get('columns.foo') is called.
// Note 'columns.' is 8 characters
return name.length > 8 ? this._columnMap : columns;
},
/**
Relays the `get()` request for the deprecated `columnset` attribute to the
`columns` attribute.
THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will
expect a Columnset instance returned from `get('columnset')`.
@method _getColumnset
@param {Object} ignored The current value stored in the `columnset` state
@param {String} name The attribute name requested
(e.g. 'columnset' or 'columnset.foo');
@deprecated This will be removed with the `columnset` attribute in a future
version.
@protected
@since 3.5.0
**/
_getColumnset: function (_, name) {
return this.get(name.replace(/^columnset/, 'columns'));
},
/**
Returns the Model class of the instance's `data` attribute ModelList. If
not set, returns the explicitly configured value.
@method _getRecordType
@param {Model} val The currently configured value
@return {Model}
**/
_getRecordType: function (val) {
// Prefer the value stored in the attribute because the attribute
// change event defaultFn sets e.newVal = this.get('recordType')
// before notifying the after() subs. But if this getter returns
// this.data.model, then after() subs would get e.newVal === previous
// model before _afterRecordTypeChange can set
// this.data.model = e.newVal
return val || (this.data && this.data.model);
},
/**
Initializes the `_columnMap` property from the configured `columns`
attribute. If `columns` is not set, but there are records in the `data`
ModelList, use
`ATTRS` of that class.
@method _initColumns
@protected
@since 3.5.0
**/
_initColumns: function () {
var columns = this.get('columns') || [],
item;
// Default column definition from the configured recordType
if (!columns.length && this.data.size()) {
// TODO: merge superclass attributes up to Model?
item = this.data.item(0);
if (item.toJSON) {
item = item.toJSON();
}
this.set('columns', keys(item));
}
this._setColumnMap(columns);
},
/**
Sets up the change event subscriptions to maintain internal state.
@method _initCoreEvents
@protected
@since 3.6.0
**/
_initCoreEvents: function () {
this._eventHandles.coreAttrChanges = this.after({
columnsChange : Y.bind('_afterColumnsChange', this),
recordTypeChange: Y.bind('_afterRecordTypeChange', this),
dataChange : Y.bind('_afterDataChange', this)
});
},
/**
Defaults the `data` attribute to an empty ModelList if not set during
construction. Uses the configured `recordType` for the ModelList's `model`
proeprty if set.
@method _initData
@protected
@return {ModelList}
@since 3.6.0
**/
_initData: function () {
var recordType = this.get('recordType'),
// TODO: LazyModelList if recordType doesn't have complex ATTRS
modelList = new Y.ModelList();
if (recordType) {
modelList.model = recordType;
}
return modelList;
},
/**
Initializes the instance's `data` property from the value of the `data`
attribute. If the attribute value is a ModelList, it is assigned directly
to `this.data`. If it is an array, a ModelList is created, its `model`
property is set to the configured `recordType` class, and it is seeded with
the array data. This ModelList is then assigned to `this.data`.
@method _initDataProperty
@param {Array|ModelList|ArrayList} data Collection of data to populate the
DataTable
@protected
@since 3.6.0
**/
_initDataProperty: function (data) {
var recordType;
if (!this.data) {
recordType = this.get('recordType');
if (data && data.each && data.toJSON) {
this.data = data;
if (recordType) {
this.data.model = recordType;
}
} else {
// TODO: customize the ModelList or read the ModelList class
// from a configuration option?
this.data = new Y.ModelList();
if (recordType) {
this.data.model = recordType;
}
}
// TODO: Replace this with an event relay for specific events.
// Using bubbling causes subscription conflicts with the models'
// aggregated change event and 'change' events from DOM elements
// inside the table (via Widget UI event).
this.data.addTarget(this);
}
},
/**
Initializes the columns, `recordType` and data ModelList.
@method initializer
@param {Object} config Configuration object passed to constructor
@protected
@since 3.5.0
**/
initializer: function (config) {
var data = config.data,
columns = config.columns,
recordType;
// Referencing config.data to allow _setData to be more stringent
// about its behavior
this._initDataProperty(data);
// Default columns from recordType ATTRS if recordType is supplied at
// construction. If no recordType is supplied, but the data is
// supplied as a non-empty array, use the keys of the first item
// as the columns.
if (!columns) {
recordType = (config.recordType || config.data === this.data) &&
this.get('recordType');
if (recordType) {
columns = keys(recordType.ATTRS);
} else if (isArray(data) && data.length) {
columns = keys(data[0]);
}
if (columns) {
this.set('columns', columns);
}
}
this._initColumns();
this._eventHandles = {};
this._initCoreEvents();
},
/**
Iterates the array of column configurations to capture all columns with a
`key` property. An map is built with column keys as the property name and
the corresponding column object as the associated value. This map is then
assigned to the instance's `_columnMap` property.
@method _setColumnMap
@param {Object[]|String[]} columns The array of column config objects
@protected
@since 3.6.0
**/
_setColumnMap: function (columns) {
var map = {};
function process(cols) {
var i, len, col, key;
for (i = 0, len = cols.length; i < len; ++i) {
col = cols[i];
key = col.key;
// First in wins for multiple columns with the same key
// because the first call to genId (in _setColumns) will
// return the same key, which will then be overwritten by the
// subsequent same-keyed column. So table.getColumn(key) would
// return the last same-keyed column.
if (key && !map[key]) {
map[key] = col;
}
//TODO: named columns can conflict with keyed columns
map[col._id] = col;
if (col.children) {
process(col.children);
}
}
}
process(columns);
this._columnMap = map;
},
/**
Translates string columns into objects with that string as the value of its
`key` property.
All columns are assigned a `_yuid` stamp and `_id` property corresponding
to the column's configured `name` or `key` property with any spaces
replaced with dashes. If the same `name` or `key` appears in multiple
columns, subsequent appearances will have their `_id` appended with an
incrementing number (e.g. if column "foo" is included in the `columns`
attribute twice, the first will get `_id` of "foo", and the second an `_id`
of "foo1"). Columns that are children of other columns will have the
`_parent` property added, assigned the column object to which they belong.
@method _setColumns
@param {null|Object[]|String[]} val Array of config objects or strings
@return {null|Object[]}
@protected
**/
_setColumns: function (val) {
var keys = {},
known = [],
knownCopies = [],
arrayIndex = Y.Array.indexOf;
function copyObj(o) {
var copy = {},
key, val, i;
known.push(o);
knownCopies.push(copy);
for (key in o) {
if (o.hasOwnProperty(key)) {
val = o[key];
if (isArray(val)) {
copy[key] = val.slice();
} else if (isObject(val, true)) {
i = arrayIndex(known, val);
copy[key] = i === -1 ? copyObj(val) : knownCopies[i];
} else {
copy[key] = o[key];
}
}
}
return copy;
}
function genId(name) {
// Sanitize the name for use in generated CSS classes.
// TODO: is there more to do for other uses of _id?
name = name.replace(/\s+/, '-');
if (keys[name]) {
name += (keys[name]++);
} else {
keys[name] = 1;
}
return name;
}
function process(cols, parent) {
var columns = [],
i, len, col, yuid;
for (i = 0, len = cols.length; i < len; ++i) {
columns[i] = // chained assignment
col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);
yuid = Y.stamp(col);
// For backward compatibility
if (!col.id) {
// Implementers can shoot themselves in the foot by setting
// this config property to a non-unique value
col.id = yuid;
}
if (col.field) {
// Field is now known as "name" to avoid confusion with data
// fields or schema.resultFields
col.name = col.field;
}
if (parent) {
col._parent = parent;
} else {
delete col._parent;
}
// Unique id based on the column's configured name or key,
// falling back to the yuid. Duplicates will have a counter
// added to the end.
col._id = genId(col.name || col.key || col.id);
if (isArray(col.children)) {
col.children = process(col.children, col);
}
}
return columns;
}
return val && process(val);
},
/**
Relays attribute assignments of the deprecated `columnset` attribute to the
`columns` attribute. If a Columnset is object is passed, its basic object
structure is mined.
@method _setColumnset
@param {Array|Columnset} val The columnset value to relay
@deprecated This will be removed with the deprecated `columnset` attribute
in a later version.
@protected
@since 3.5.0
**/
_setColumnset: function (val) {
this.set('columns', val);
return isArray(val) ? val : INVALID;
},
/**
Accepts an object with `each` and `getAttrs` (preferably a ModelList or
subclass) or an array of data objects. If an array is passes, it will
create a ModelList to wrap the data. In doing so, it will set the created
ModelList's `model` property to the class in the `recordType` attribute,
which will be defaulted if not yet set.
If the `data` property is already set with a ModelList, passing an array as
the value will call the ModelList's `reset()` method with that array rather
than replacing the stored ModelList wholesale.
Any non-ModelList-ish and non-array value is invalid.
@method _setData
@protected
@since 3.5.0
**/
_setData: function (val) {
if (val === null) {
val = [];
}
if (isArray(val)) {
this._initDataProperty();
// silent to prevent subscribers to both reset and dataChange
// from reacting to the change twice.
// TODO: would it be better to return INVALID to silence the
// dataChange event, or even allow both events?
this.data.reset(val, { silent: true });
// Return the instance ModelList to avoid storing unprocessed
// data in the state and their vivified Model representations in
// the instance's data property. Decreases memory consumption.
val = this.data;
} else if (!val || !val.each || !val.toJSON) {
// ModelList/ArrayList duck typing
val = INVALID;
}
return val;
},
/**
Relays the value assigned to the deprecated `recordset` attribute to the
`data` attribute. If a Recordset instance is passed, the raw object data
will be culled from it.
@method _setRecordset
@param {Object[]|Recordset} val The recordset value to relay
@deprecated This will be removed with the deprecated `recordset` attribute
in a later version.
@protected
@since 3.5.0
**/
_setRecordset: function (val) {
var data;
if (val && Y.Recordset && val instanceof Y.Recordset) {
data = [];
val.each(function (record) {
data.push(record.get('data'));
});
val = data;
}
this.set('data', val);
return val;
},
/**
Accepts a Base subclass (preferably a Model subclass). Alternately, it will
generate a custom Model subclass from an array of attribute names or an
object defining attributes and their respective configurations (it is
assigned as the `ATTRS` of the new class).
Any other value is invalid.
@method _setRecordType
@param {Function|String[]|Object} val The Model subclass, array of
attribute names, or the `ATTRS` definition for a custom model
subclass
@return {Function} A Base/Model subclass
@protected
@since 3.5.0
**/
_setRecordType: function (val) {
var modelClass;
// Duck type based on known/likely consumed APIs
if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {
modelClass = val;
} else if (isObject(val)) {
modelClass = this._createRecordClass(val);
}
return modelClass || INVALID;
}
});
/**
_This is a documentation entry only_
Columns are described by object literals with a set of properties.
There is not an actual `DataTable.Column` class.
However, for the purpose of documenting it, this pseudo-class is declared here.
DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns)
attribute. Each entry in this array is a column definition which may contain
any combination of the properties listed below.
There are no mandatory properties though a column will usually have a
[key](#property_key) property to reference the data it is supposed to show.
The [columns](DataTable.html#attr_columns) attribute can accept a plain string
in lieu of an object literal, which is the equivalent of an object with the
[key](#property_key) property set to that string.
@class DataTable.Column
*/
/**
Binds the column values to the named property in the [data](DataTable.html#attr_data).
Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),
or [cellTemplate](#property_cellTemplate) is used to populate the content.
It should not be set if [children](#property_children) is set.
The value is used for the [\_id](#property__id) property unless the [name](#property_name)
property is also set.
{ key: 'username' }
The above column definition can be reduced to this:
'username'
@property key
@type String
*/
/**
An identifier that can be used to locate a column via
[getColumn](DataTable.html#method_getColumn)
or style columns with class `yui3-datatable-col-NAME` after dropping characters
that are not valid for CSS class names.
It defaults to the [key](#property_key).
The value is used for the [\_id](#property__id) property.
{ name: 'fullname', formatter: ... }
@property name
@type String
*/
/**
An alias for [name](#property_name) for backward compatibility.
{ field: 'fullname', formatter: ... }
@property field
@type String
*/
/**
Overrides the default unique id assigned `<th id="HERE">`.
__Use this with caution__, since it can result in
duplicate ids in the DOM.
{
name: 'checkAll',
id: 'check-all',
label: ...
formatter: ...
}
@property id
@type String
*/
/**
HTML to populate the header `<th>` for the column.
It defaults to the value of the [key](#property_key) property or the text
`Column n` where _n_ is an ordinal number.
{ key: 'MfgvaPrtNum', label: 'Part Number' }
@property label
@type {String}
*/
/**
Used to create stacked headers.
Child columns may also contain `children`. There is no limit
to the depth of nesting.
Columns configured with `children` are for display only and
<strong>should not</strong> be configured with a [key](#property_key).
Configurations relating to the display of data, such as
[formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),
[emptyCellValue](#property_emptyCellValue), etc. are ignored.
{ label: 'Name', children: [
{ key: 'firstName', label: 'First`},
{ key: 'lastName', label: 'Last`}
]}
@property children
@type Array
*/
/**
Assigns the value `<th abbr="HERE">`.
{
key : 'forecast',
label: '1yr Target Forecast',
abbr : 'Forecast'
}
@property abbr
@type String
*/
/**
Assigns the value `<th title="HERE">`.
{
key : 'forecast',
label: '1yr Target Forecast',
title: 'Target Forecast for the Next 12 Months'
}
@property title
@type String
*/
/**
Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE)
used by `Y.DataTable.HeaderView` to render the header cell
for this column. This is necessary when more control is
needed over the markup for the header itself, rather than
its content.
Use the [label](#property_label) configuration if you don't need to
customize the `<th>` iteself.
Implementers are strongly encouraged to preserve at least
the `{id}` and `{_id}` placeholders in the custom value.
{
headerTemplate:
'<th id="{id}" ' +
'title="Unread" ' +
'class="{className}" ' +
'{_id}>●</th>'
}
@property headerTemplate
@type HTML
*/
/**
Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE)
used by `Y.DataTable.BodyView` to render the data cells
for this column. This is necessary when more control is
needed over the markup for the `<td>` itself, rather than
its content.
{
key: 'id',
cellTemplate:
'<td class="{className}">' +
'<input type="checkbox" ' +
'id="{content}">' +
'</td>'
}
@property cellTemplate
@type String
*/
/**
String or function used to translate the raw record data for each cell in a
given column into a format better suited to display.
If it is a string, it will initially be assumed to be the name of one of the
formatting functions in
[Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html).
If one such formatting function exists, it will be used.
If no such named formatter is found, it will be assumed to be a template
string and will be expanded. The placeholders can contain the key to any
field in the record or the placeholder `{value}` which represents the value
of the current field.
If the value is a function, it will be assumed to be a formatting function.
A formatting function receives a single argument, an object with the following properties:
* __value__ The raw value from the record Model to populate this cell.
Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.
* __data__ The Model data for this row in simple object format.
* __record__ The Model for this row.
* __column__ The column configuration object.
* __className__ A string of class names to add `<td class="HERE">` in addition to
the column class and any classes in the column's className configuration.
* __rowIndex__ The index of the current Model in the ModelList.
Typically correlates to the row index as well.
* __rowClass__ A string of css classes to add `<tr class="HERE"><td....`
This is useful to avoid the need for nodeFormatters to add classes to the containing row.
The formatter function may return a string value that will be used for the cell
contents or it may change the value of the `value`, `className` or `rowClass`
properties which well then be used to format the cell. If the value for the cell
is returned in the `value` property of the input argument, no value should be returned.
{
key: 'name',
formatter: 'link', // named formatter
linkFrom: 'website' // extra column property for link formatter
},
{
key: 'cost',
formatter: '${value}' // formatter template string
//formatter: '${cost}' // same result but less portable
},
{
name: 'Name', // column does not have associated field value
// thus, it uses name instead of key
formatter: '{firstName} {lastName}' // template references other fields
},
{
key: 'price',
formatter: function (o) { // function both returns a string to show
if (o.value > 3) { // and a className to apply to the cell
o.className += 'expensive';
}
return '$' + o.value.toFixed(2);
}
},
@property formatter
@type String || Function
*/
/**
Used to customize the content of the data cells for this column.
`nodeFormatter` is significantly slower than [formatter](#property_formatter)
and should be avoided if possible. Unlike [formatter](#property_formatter),
`nodeFormatter` has access to the `<td>` element and its ancestors.
The function provided is expected to fill in the `<td>` element itself.
__Node formatters should return `false`__ except in certain conditions as described
in the users guide.
The function receives a single object
argument with the following properties:
* __td__ The `<td>` Node for this cell.
* __cell__ If the cell `<td> contains an element with class `yui3-datatable-liner,
this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior).
* __value__ The raw value from the record Model to populate this cell.
Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.
* __data__ The Model data for this row in simple object format.
* __record__ The Model for this row.
* __column__ The column configuration object.
* __rowIndex__ The index of the current Model in the ModelList.
_Typically_ correlates to the row index as well.
@example
nodeFormatter: function (o) {
if (o.value < o.data.quota) {
o.td.setAttribute('rowspan', 2);
o.td.setAttribute('data-term-id', this.record.get('id'));
o.td.ancestor().insert(
'<tr><td colspan"3">' +
'<button class="term">terminate</button>' +
'</td></tr>',
'after');
}
o.cell.setHTML(o.value);
return false;
}
@property nodeFormatter
@type Function
*/
/**
Provides the default value to populate the cell if the data
for that cell is `undefined`, `null`, or an empty string.
{
key: 'price',
emptyCellValue: '???'
}
@property emptyCellValue
@type {String} depending on the setting of allowHTML
*/
/**
Skips the security step of HTML escaping the value for cells
in this column.
This is also necessary if [emptyCellValue](#property_emptyCellValue)
is set with an HTML string.
`nodeFormatter`s ignore this configuration. If using a
`nodeFormatter`, it is recommended to use
[Y.Escape.html()](Escape.html#method_html)
on any user supplied content that is to be displayed.
{
key: 'preview',
allowHTML: true
}
@property allowHTML
@type Boolean
*/
/**
A string of CSS classes that will be added to the `<td>`'s
`class` attribute.
Note, all cells will automatically have a class in the
form of "yui3-datatable-col-XXX" added to the `<td>`, where
XXX is the column's configured `name`, `key`, or `id` (in
that order of preference) sanitized from invalid characters.
{
key: 'symbol',
className: 'no-hide'
}
@property className
@type String
*/
/**
(__read-only__) The unique identifier assigned
to each column. This is used for the `id` if not set, and
the `_id` if none of [name](#property_name),
[field](#property_field), [key](#property_key), or [id](#property_id) are
set.
@property _yuid
@type String
@protected
*/
/**
(__read-only__) A unique-to-this-instance name
used extensively in the rendering process. It is also used
to create the column's classname, as the input name
`table.getColumn(HERE)`, and in the column header's
`<th data-yui3-col-id="HERE">`.
The value is populated by the first of [name](#property_name),
[field](#property_field), [key](#property_key), [id](#property_id),
or [_yuid](#property__yuid) to have a value. If that value
has already been used (such as when multiple columns have
the same `key`), an incrementer is added to the end. For
example, two columns with `key: "id"` will have `_id`s of
"id" and "id2". `table.getColumn("id")` will return the
first column, and `table.getColumn("id2")` will return the
second.
@property _id
@type String
@protected
*/
/**
(__read-only__) Used by
`Y.DataTable.HeaderView` when building stacked column
headers.
@property _colspan
@type Integer
@protected
*/
/**
(__read-only__) Used by
`Y.DataTable.HeaderView` when building stacked column
headers.
@property _rowspan
@type Integer
@protected
*/
/**
(__read-only__) Assigned to all columns in a
column's `children` collection. References the parent
column object.
@property _parent
@type DataTable.Column
@protected
*/
/**
(__read-only__) Array of the `id`s of the
column and all parent columns. Used by
`Y.DataTable.BodyView` to populate `<td headers="THIS">`
when a cell references more than one header.
@property _headers
@type Array
@protected
*/
}, '3.17.1', {"requires": ["escape", "model-list", "node-event-delegate"]});
|
src/components/prompts/ConfirmLeave.js | shp54/cliff-effects | import React from 'react';
/**
* Ask the user for confirmation to leave the page.
* @extends React.Component
*
* @param props {object}
* @param props.isBlocking {boolean} - Whether the component should block
* @param props.message {string} - The message the browser shows, maybe
*/
class ConfirmLeave extends React.Component {
static defaultProps = { isBlocking: true };
confirm = (event) => {
if (!this.props.isBlocking) {
return; // do not block unload
}
return (event.returnValue = this.props.message || '');
};
componentDidMount() {
window.addEventListener('beforeunload', this.confirm);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.confirm);
}
render() {
return null;
}
}
export default ConfirmLeave;
|
subfind_web/ui/src/components/AdminLTE.js | thongdong7/subfind | import React from 'react'
export default class AdminLTE extends React.Component {
render() {
return (
<div className="container">
{this.props.children}
</div>
)
}
}
|
examples/todos-with-undo/components/Footer.js | edge/redux | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer
|
src/components/video_list_item.js | izabelka/redux-simple-starter | import React from 'react';
const VideoListItem = ({video, onVideoSelect}) => {
const imageUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VideoListItem;
|
examples/huge-apps/components/Dashboard.js | neebz/react-router | import React from 'react';
import { Link } from 'react-router';
class Dashboard extends React.Component {
render () {
let { courses } = this.props;
return (
<div>
<h2>Super Scalable Apps</h2>
<p>
Open the network tab as you navigate. Notice that only the amount of
your app that is required is actually downloaded as you navigate
around. Even the route configuration objects are loaded on the fly.
This way, a new route added deep in your app will not affect the
initial bundle of your application.
</p>
<h2>Courses</h2>{' '}
<ul>
{courses.map(course => (
<li key={course.id}>
<Link to={`/course/${course.id}`}>{course.name}</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Dashboard;
|
src/svg-icons/action/swap-vert.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSwapVert = (props) => (
<SvgIcon {...props}>
<path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/>
</SvgIcon>
);
ActionSwapVert = pure(ActionSwapVert);
ActionSwapVert.displayName = 'ActionSwapVert';
ActionSwapVert.muiName = 'SvgIcon';
export default ActionSwapVert;
|
src/layouts/CoreLayout.js | todvora/extrade | import React from 'react'
import { Link } from 'react-router'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.min.js'
import '../styles/core.scss'
import '../styles/main.less'
// Note: Stateless/function components *will not* hot reload!
// react-transform *only* works on component classes.
//
// Since layouts rarely change, they are a good place to
// leverage React's new Statelesss Functions:
// https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
//
// CoreLayout is a pure function of it's props, so we can
// define it with a plain javascript function...
function CoreLayout ({ children }) {
return (
<div>
<div className='navbar navbar-default navbar-static-top' role='navigation'>
<div className='container'>
<div className='navbar-header'>
<button className='navbar-toggle' type='button' data-toggle='collapse' data-target='.navbar-collapse'/>
<span className='span sr-only'>Toggle navigation</span>
<span className='icon-bar'></span>
<span className='icon-bar'></span>
<span className='icon-bar'></span>
<Link className='navbar-brand' to='/'>Statistiky zahraničního obchodu</Link>
</div>
<div className='navbar-collapse collapse'>
<ul className='nav navbar-nav navbar-right'>
<li><Link to='/'>Úvod</Link></li>
<li><Link to='/about'>O aplikaci</Link></li>
<li><Link to='/contact'>Kontakt</Link></li>
</ul>
</div>
</div>
</div>
<div className='container'>
{children}
</div>
</div>
)
}
CoreLayout.propTypes = {
children: React.PropTypes.element
}
export default CoreLayout
|
src/components/student/question.js | scottbrassfield/Assess.js | import React from 'react'
const Question = ({ problem }) => (
<div style={{fontSize: 24}}>
{problem.question}
</div>
)
export default Question
|
src/routes.js | Ftornik/forwardteam.space | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import * as Page from 'containers';
const componentRoutes = (
<Route>
<IndexRoute component={ Page.Home }/>
<Route path="id/:id" component={ Page.User }/>
<Route path="team/:id" component={ Page.Team }/>
<Route path="*" component={ Page.NotFound } status={ 404 }/>
</Route>
);
/* eslint-disable react/jsx-no-bind */
export default () => {
return (
<Route path="/" component={ Page.App }>
{ componentRoutes }
</Route>
);
};
|
ajax/libs/react-instantsearch/5.3.1/Connectors.min.js | cdnjs/cdnjs | /*! React InstantSearch 5.3.1 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e.ReactInstantSearch=e.ReactInstantSearch||{},e.ReactInstantSearch.Connectors={}),e.React)}(this,function(e,v){"use strict";var m="default"in v?v.default:v,t="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function r(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}var i=r,a=n;function o(t){if(i===setTimeout)return setTimeout(t,0);if((i===r||!i)&&setTimeout)return i=setTimeout,setTimeout(t,0);try{return i(t,0)}catch(e){try{return i.call(null,t,0)}catch(e){return i.call(this,t,0)}}}"function"==typeof t.setTimeout&&(i=setTimeout),"function"==typeof t.clearTimeout&&(a=clearTimeout);var s,c=[],u=!1,f=-1;function l(){u&&s&&(u=!1,s.length?c=s.concat(c):f=-1,c.length&&h())}function h(){if(!u){var e=o(l);u=!0;for(var t=c.length;t;){for(s=c,c=[];++f<t;)s&&s[f].run();f=-1,t=c.length}s=null,u=!1,function(t){if(a===clearTimeout)return clearTimeout(t);if((a===n||!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)}}}(e)}}function d(e,t){this.fun=e,this.array=t}d.prototype.run=function(){this.fun.apply(null,this.array)};function p(){}var g=p,y=p,b=p,R=p,x=p,F=p,_=p;var j=t.performance||{},w=j.now||j.mozNow||j.msNow||j.oNow||j.webkitNow||function(){return(new Date).getTime()};var P=new Date;var O={nextTick:function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];c.push(new d(e,t)),1!==c.length||u||o(h)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:g,addListener:y,once:b,off:R,removeListener:x,removeAllListeners:F,emit:_,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*w.call(j),r=Math.floor(t),n=Math.floor(t%1*1e9);return e&&(r-=e[0],(n-=e[1])<0&&(r--,n+=1e9)),[r,n]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-P)/1e3}},E="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function S(e,t){return e(t={exports:{}},t.exports),t.exports}function T(e){return function(){return e}}var A=function(){};A.thatReturns=T,A.thatReturnsFalse=T(!1),A.thatReturnsTrue=T(!0),A.thatReturnsNull=T(null),A.thatReturnsThis=function(){return this},A.thatReturnsArgument=function(e){return e};var N=A;var C=function(e,t,r,n,i,a,o,s){if(!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[r,n,i,a,o,s],f=0;(c=new Error(t.replace(/%s/g,function(){return u[f++]}))).name="Invariant Violation"}throw c.framesToPop=1,c}},I=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable;(function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}})()&&Object.assign;var M=S(function(e){e.exports=function(){function e(e,t,r,n,i,a){"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"!==a&&C(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}var r={array:e.isRequired=e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return r.checkPropTypes=N,r.PropTypes=r}()});var D=function(){this.__data__=[],this.size=0};var B=function(e,t){return e===t||e!=e&&t!=t};var L=function(e,t){for(var r=e.length;r--;)if(B(e[r][0],t))return r;return-1},k=Array.prototype.splice;var U=function(e){var t=this.__data__,r=L(t,e);return!(r<0||(r==t.length-1?t.pop():k.call(t,r,1),--this.size,0))};var V=function(e){var t=this.__data__,r=L(t,e);return r<0?void 0:t[r][1]};var q=function(e){return-1<L(this.__data__,e)};var W=function(e,t){var r=this.__data__,n=L(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};function z(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}z.prototype.clear=D,z.prototype.delete=U,z.prototype.get=V,z.prototype.has=q,z.prototype.set=W;var $=z;var J=function(){this.__data__=new $,this.size=0};var Y=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r};var G=function(e){return this.__data__.get(e)};var K=function(e){return this.__data__.has(e)},Z="object"==typeof E&&E&&E.Object===Object&&E,X="object"==typeof self&&self&&self.Object===Object&&self,ee=Z||X||Function("return this")(),te=ee.Symbol,re=Object.prototype,ne=re.hasOwnProperty,ie=re.toString,ae=te?te.toStringTag:void 0;var oe=function(e){var t=ne.call(e,ae),r=e[ae];try{e[ae]=void 0}catch(e){}var n=ie.call(e);return t?e[ae]=r:delete e[ae],n},se=Object.prototype.toString;var ce=function(e){return se.call(e)},ue=te?te.toStringTag:void 0;var fe=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ue&&ue in Object(e)?oe(e):ce(e)};var le=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)};var he,de=function(e){if(!le(e))return!1;var t=fe(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},pe=ee["__core-js_shared__"],ve=(he=/[^.]+$/.exec(pe&&pe.keys&&pe.keys.IE_PROTO||""))?"Symbol(src)_1."+he:"";var me=function(e){return!!ve&&ve in e},ge=Function.prototype.toString;var ye=function(e){if(null!=e){try{return ge.call(e)}catch(e){}try{return e+""}catch(e){}}return""},be=/^\[object .+?Constructor\]$/,Re=Function.prototype,xe=Object.prototype,Fe=Re.toString,_e=xe.hasOwnProperty,je=RegExp("^"+Fe.call(_e).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var we=function(e){return!(!le(e)||me(e))&&(de(e)?je:be).test(ye(e))};var Pe=function(e,t){return null==e?void 0:e[t]};var Se=function(e,t){var r=Pe(e,t);return we(r)?r:void 0},Oe=Se(ee,"Map"),Ee=Se(Object,"create");var Te=function(){this.__data__=Ee?Ee(null):{},this.size=0};var Ae=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Ne=Object.prototype.hasOwnProperty;var Ce=function(e){var t=this.__data__;if(Ee){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return Ne.call(t,e)?t[e]:void 0},Ie=Object.prototype.hasOwnProperty;var He=function(e){var t=this.__data__;return Ee?void 0!==t[e]:Ie.call(t,e)};var Qe=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Ee&&void 0===t?"__lodash_hash_undefined__":t,this};function Me(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Me.prototype.clear=Te,Me.prototype.delete=Ae,Me.prototype.get=Ce,Me.prototype.has=He,Me.prototype.set=Qe;var De=Me;var Be=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Le=function(e,t){var r=e.__data__;return Be(t)?r["string"==typeof t?"string":"hash"]:r.map};var ke=function(e){var t=Le(this,e).delete(e);return this.size-=t?1:0,t};var Ue=function(e){return Le(this,e).get(e)};var Ve=function(e){return Le(this,e).has(e)};var qe=function(e,t){var r=Le(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this};function We(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}We.prototype.clear=function(){this.size=0,this.__data__={hash:new De,map:new(Oe||$),string:new De}},We.prototype.delete=ke,We.prototype.get=Ue,We.prototype.has=Ve,We.prototype.set=qe;var ze=We;var $e=function(e,t){var r=this.__data__;if(r instanceof $){var n=r.__data__;if(!Oe||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new ze(n)}return r.set(e,t),this.size=r.size,this};function Je(e){var t=this.__data__=new $(e);this.size=t.size}Je.prototype.clear=J,Je.prototype.delete=Y,Je.prototype.get=G,Je.prototype.has=K,Je.prototype.set=$e;var Ye=Je;var Ge=function(e){return this.__data__.has(e)};function Ke(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new ze;++t<r;)this.add(e[t])}Ke.prototype.add=Ke.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},Ke.prototype.has=Ge;var Ze=Ke;var Xe=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1};var et=function(e,t){return e.has(t)};var tt=function(e,t,r,n,i,a){var o=1&r,s=e.length,c=t.length;if(s!=c&&!(o&&s<c))return!1;var u=a.get(e);if(u&&a.get(t))return u==t;var f=-1,l=!0,h=2&r?new Ze:void 0;for(a.set(e,t),a.set(t,e);++f<s;){var d=e[f],p=t[f];if(n)var v=o?n(p,d,f,t,e,a):n(d,p,f,e,t,a);if(void 0!==v){if(v)continue;l=!1;break}if(h){if(!Xe(t,function(e,t){if(!et(h,t)&&(d===e||i(d,e,r,n,a)))return h.push(t)})){l=!1;break}}else if(d!==p&&!i(d,p,r,n,a)){l=!1;break}}return a.delete(e),a.delete(t),l},rt=ee.Uint8Array;var nt=function(e){var r=-1,n=Array(e.size);return e.forEach(function(e,t){n[++r]=[t,e]}),n};var it=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r},at=te?te.prototype:void 0,ot=at?at.valueOf:void 0;var st=function(e,t,r,n,i,a,o){switch(r){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!a(new rt(e),new rt(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return B(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var s=nt;case"[object Set]":var c=1&n;if(s||(s=it),e.size!=t.size&&!c)return!1;var u=o.get(e);if(u)return u==t;n|=2,o.set(e,t);var f=tt(s(e),s(t),n,i,a,o);return o.delete(e),f;case"[object Symbol]":if(ot)return ot.call(e)==ot.call(t)}return!1};var ct=function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e},ut=Array.isArray;var ft=function(e,t,r){var n=t(e);return ut(e)?n:ct(n,r(e))};var lt=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a};var ht=function(){return[]},dt=Object.prototype.propertyIsEnumerable,pt=Object.getOwnPropertySymbols,vt=pt?function(t){return null==t?[]:(t=Object(t),lt(pt(t),function(e){return dt.call(t,e)}))}:ht;var mt=function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n};var gt=function(e){return null!=e&&"object"==typeof e};var yt=function(e){return gt(e)&&"[object Arguments]"==fe(e)},bt=Object.prototype,Rt=bt.hasOwnProperty,xt=bt.propertyIsEnumerable,Ft=yt(function(){return arguments}())?yt:function(e){return gt(e)&&Rt.call(e,"callee")&&!xt.call(e,"callee")};var _t=function(){return!1},jt=S(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r?ee.Buffer:void 0,a=(i?i.isBuffer:void 0)||_t;e.exports=a}),wt=/^(?:0|[1-9]\d*)$/;var Pt=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&wt.test(e))&&-1<e&&e%1==0&&e<t};var St=function(e){return"number"==typeof e&&-1<e&&e%1==0&&e<=9007199254740991},Ot={};Ot["[object Float32Array]"]=Ot["[object Float64Array]"]=Ot["[object Int8Array]"]=Ot["[object Int16Array]"]=Ot["[object Int32Array]"]=Ot["[object Uint8Array]"]=Ot["[object Uint8ClampedArray]"]=Ot["[object Uint16Array]"]=Ot["[object Uint32Array]"]=!0,Ot["[object Arguments]"]=Ot["[object Array]"]=Ot["[object ArrayBuffer]"]=Ot["[object Boolean]"]=Ot["[object DataView]"]=Ot["[object Date]"]=Ot["[object Error]"]=Ot["[object Function]"]=Ot["[object Map]"]=Ot["[object Number]"]=Ot["[object Object]"]=Ot["[object RegExp]"]=Ot["[object Set]"]=Ot["[object String]"]=Ot["[object WeakMap]"]=!1;var Et=function(e){return gt(e)&&St(e.length)&&!!Ot[fe(e)]};var Tt=function(t){return function(e){return t(e)}},At=S(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r&&Z.process,a=function(){try{return i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=a}),Nt=At&&At.isTypedArray,Ct=Nt?Tt(Nt):Et,It=Object.prototype.hasOwnProperty;var Ht=function(e,t){var r=ut(e),n=!r&&Ft(e),i=!r&&!n&&jt(e),a=!r&&!n&&!i&&Ct(e),o=r||n||i||a,s=o?mt(e.length,String):[],c=s.length;for(var u in e)!t&&!It.call(e,u)||o&&("length"==u||i&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||Pt(u,c))||s.push(u);return s},Qt=Object.prototype;var Mt=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Qt)};var Dt=function(t,r){return function(e){return t(r(e))}},Bt=Dt(Object.keys,Object),Lt=Object.prototype.hasOwnProperty;var kt=function(e){if(!Mt(e))return Bt(e);var t=[];for(var r in Object(e))Lt.call(e,r)&&"constructor"!=r&&t.push(r);return t};var Ut=function(e){return null!=e&&St(e.length)&&!de(e)};var Vt=function(e){return Ut(e)?Ht(e):kt(e)};var qt=function(e){return ft(e,Vt,vt)},Wt=Object.prototype.hasOwnProperty;var zt=function(e,t,r,n,i,a){var o=1&r,s=qt(e),c=s.length;if(c!=qt(t).length&&!o)return!1;for(var u=c;u--;){var f=s[u];if(!(o?f in t:Wt.call(t,f)))return!1}var l=a.get(e);if(l&&a.get(t))return l==t;var h=!0;a.set(e,t),a.set(t,e);for(var d=o;++u<c;){var p=e[f=s[u]],v=t[f];if(n)var m=o?n(v,p,f,t,e,a):n(p,v,f,e,t,a);if(!(void 0===m?p===v||i(p,v,r,n,a):m)){h=!1;break}d||(d="constructor"==f)}if(h&&!d){var g=e.constructor,y=t.constructor;g!=y&&"constructor"in e&&"constructor"in t&&!("function"==typeof g&&g instanceof g&&"function"==typeof y&&y instanceof y)&&(h=!1)}return a.delete(e),a.delete(t),h},$t=Se(ee,"DataView"),Jt=Se(ee,"Promise"),Yt=Se(ee,"Set"),Gt=Se(ee,"WeakMap"),Kt="[object Map]",Zt="[object Promise]",Xt="[object Set]",er="[object WeakMap]",tr="[object DataView]",rr=ye($t),nr=ye(Oe),ir=ye(Jt),ar=ye(Yt),or=ye(Gt),sr=fe;($t&&sr(new $t(new ArrayBuffer(1)))!=tr||Oe&&sr(new Oe)!=Kt||Jt&&sr(Jt.resolve())!=Zt||Yt&&sr(new Yt)!=Xt||Gt&&sr(new Gt)!=er)&&(sr=function(e){var t=fe(e),r="[object Object]"==t?e.constructor:void 0,n=r?ye(r):"";if(n)switch(n){case rr:return tr;case nr:return Kt;case ir:return Zt;case ar:return Xt;case or:return er}return t});var cr=sr,ur="[object Arguments]",fr="[object Array]",lr="[object Object]",hr=Object.prototype.hasOwnProperty;var dr=function(e,t,r,n,i,a){var o=ut(e),s=ut(t),c=o?fr:cr(e),u=s?fr:cr(t),f=(c=c==ur?lr:c)==lr,l=(u=u==ur?lr:u)==lr,h=c==u;if(h&&jt(e)){if(!jt(t))return!1;f=!(o=!0)}if(h&&!f)return a||(a=new Ye),o||Ct(e)?tt(e,t,r,n,i,a):st(e,t,c,r,n,i,a);if(!(1&r)){var d=f&&hr.call(e,"__wrapped__"),p=l&&hr.call(t,"__wrapped__");if(d||p){var v=d?e.value():e,m=p?t.value():t;return a||(a=new Ye),i(v,m,r,n,a)}}return!!h&&(a||(a=new Ye),zt(e,t,r,n,i,a))};var pr=function e(t,r,n,i,a){return t===r||(null==t||null==r||!gt(t)&&!gt(r)?t!=t&&r!=r:dr(t,r,n,i,e,a))};var vr=function(e,t,r,n){var i=r.length,a=i,o=!n;if(null==e)return!a;for(e=Object(e);i--;){var s=r[i];if(o&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++i<a;){var c=(s=r[i])[0],u=e[c],f=s[1];if(o&&s[2]){if(void 0===u&&!(c in e))return!1}else{var l=new Ye;if(n)var h=n(u,f,c,e,t,l);if(!(void 0===h?pr(f,u,3,n,l):h))return!1}}return!0};var mr=function(e){return e==e&&!le(e)};var gr=function(e){for(var t=Vt(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,mr(i)]}return t};var yr=function(t,r){return function(e){return null!=e&&e[t]===r&&(void 0!==r||t in Object(e))}};var br=function(t){var r=gr(t);return 1==r.length&&r[0][2]?yr(r[0][0],r[0][1]):function(e){return e===t||vr(e,t,r)}};var Rr=function(e){return"symbol"==typeof e||gt(e)&&"[object Symbol]"==fe(e)},xr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fr=/^\w*$/;var _r=function(e,t){if(ut(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!Rr(e))||Fr.test(e)||!xr.test(e)||null!=t&&e in Object(t)},jr="Expected a function";function wr(i,a){if("function"!=typeof i||null!=a&&"function"!=typeof a)throw new TypeError(jr);var o=function(){var e=arguments,t=a?a.apply(this,e):e[0],r=o.cache;if(r.has(t))return r.get(t);var n=i.apply(this,e);return o.cache=r.set(t,n)||r,n};return o.cache=new(wr.Cache||ze),o}wr.Cache=ze;var Pr=wr;var Sr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Or=/\\(\\)?/g,Er=function(e){var t=Pr(e,function(e){return 500===r.size&&r.clear(),e}),r=t.cache;return t}(function(e){var i=[];return 46===e.charCodeAt(0)&&i.push(""),e.replace(Sr,function(e,t,r,n){i.push(r?n.replace(Or,"$1"):t||e)}),i});var Tr=function(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i},Ar=1/0,Nr=te?te.prototype:void 0,Cr=Nr?Nr.toString:void 0;var Ir=function e(t){if("string"==typeof t)return t;if(ut(t))return Tr(t,e)+"";if(Rr(t))return Cr?Cr.call(t):"";var r=t+"";return"0"==r&&1/t==-Ar?"-0":r};var Hr=function(e){return null==e?"":Ir(e)};var Qr=function(e,t){return ut(e)?e:_r(e,t)?[e]:Er(Hr(e))};var Mr=function(e){if("string"==typeof e||Rr(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t};var Dr=function(e,t){for(var r=0,n=(t=Qr(t,e)).length;null!=e&&r<n;)e=e[Mr(t[r++])];return r&&r==n?e:void 0};var Br=function(e,t,r){var n=null==e?void 0:Dr(e,t);return void 0===n?r:n};var Lr=function(e,t){return null!=e&&t in Object(e)};var kr=function(e,t,r){for(var n=-1,i=(t=Qr(t,e)).length,a=!1;++n<i;){var o=Mr(t[n]);if(!(a=null!=e&&r(e,o)))break;e=e[o]}return a||++n!=i?a:!!(i=null==e?0:e.length)&&St(i)&&Pt(o,i)&&(ut(e)||Ft(e))};var Ur=function(e,t){return null!=e&&kr(e,t,Lr)};var Vr=function(r,n){return _r(r)&&mr(n)?yr(Mr(r),n):function(e){var t=Br(e,r);return void 0===t&&t===n?Ur(e,r):pr(n,t,3)}};var qr=function(e){return e};var Wr=function(t){return function(e){return null==e?void 0:e[t]}};var zr=function(t){return function(e){return Dr(e,t)}};var $r=function(e){return _r(e)?Wr(Mr(e)):zr(e)};var Jr=function(e){return"function"==typeof e?e:null==e?qr:"object"==typeof e?ut(e)?Vr(e[0],e[1]):br(e):$r(e)};var Yr=function(o){return function(e,t,r){var n=Object(e);if(!Ut(e)){var i=Jr(t,3);e=Vt(e),t=function(e){return i(n[e],e,n)}}var a=o(e,t,r);return-1<a?n[i?e[a]:a]:void 0}};var Gr=function(e,t,r,n){for(var i=e.length,a=r+(n?1:-1);n?a--:++a<i;)if(t(e[a],a,e))return a;return-1},Kr=/^\s+|\s+$/g,Zr=/^[-+]0x[0-9a-f]+$/i,Xr=/^0b[01]+$/i,en=/^0o[0-7]+$/i,tn=parseInt;var rn=function(e){if("number"==typeof e)return e;if(Rr(e))return NaN;if(le(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=le(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Kr,"");var r=Xr.test(e);return r||en.test(e)?tn(e.slice(2),r?2:8):Zr.test(e)?NaN:+e};var nn=function(e){return e?(e=rn(e))!==1/0&&e!==-1/0?e==e?e:0:17976931348623157e292*(e<0?-1:1):0===e?e:0};var an=function(e){var t=nn(e),r=t%1;return t==t?r?t-r:t:0},on=Math.max;var sn=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:an(r);return i<0&&(i=on(n+i,0)),Gr(e,Jr(t,3),i)},cn=Yr(sn),un=Object.prototype.hasOwnProperty;var fn=function(e){if(null==e)return!0;if(Ut(e)&&(ut(e)||"string"==typeof e||"function"==typeof e.splice||jt(e)||Ct(e)||Ft(e)))return!e.length;var t=cr(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(Mt(e))return!kt(e).length;for(var r in e)if(un.call(e,r))return!1;return!0};var ln=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e},hn=function(){try{var e=Se(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();var dn=function(e,t,r){"__proto__"==t&&hn?hn(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r},pn=Object.prototype.hasOwnProperty;var vn=function(e,t,r){var n=e[t];pn.call(e,t)&&B(n,r)&&(void 0!==r||t in e)||dn(e,t,r)};var mn=function(e,t,r,n){var i=!r;r||(r={});for(var a=-1,o=t.length;++a<o;){var s=t[a],c=n?n(r[s],e[s],s,r,e):void 0;void 0===c&&(c=e[s]),i?dn(r,s,c):vn(r,s,c)}return r};var gn=function(e,t){return e&&mn(t,Vt(t),e)};var yn=function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t},bn=Object.prototype.hasOwnProperty;var Rn=function(e){if(!le(e))return yn(e);var t=Mt(e),r=[];for(var n in e)("constructor"!=n||!t&&bn.call(e,n))&&r.push(n);return r};var xn=function(e){return Ut(e)?Ht(e,!0):Rn(e)};var Fn=function(e,t){return e&&mn(t,xn(t),e)},_n=S(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r?ee.Buffer:void 0,a=i?i.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var r=e.length,n=a?a(r):new e.constructor(r);return e.copy(n),n}});var jn=function(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t};var wn=function(e,t){return mn(e,vt(e),t)},Pn=Dt(Object.getPrototypeOf,Object),Sn=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)ct(t,vt(e)),e=Pn(e);return t}:ht;var On=function(e,t){return mn(e,Sn(e),t)};var En=function(e){return ft(e,xn,Sn)},Tn=Object.prototype.hasOwnProperty;var An=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&Tn.call(e,"index")&&(r.index=e.index,r.input=e.input),r};var Nn=function(e){var t=new e.constructor(e.byteLength);return new rt(t).set(new rt(e)),t};var Cn=function(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)},In=/\w*$/;var Hn=function(e){var t=new e.constructor(e.source,In.exec(e));return t.lastIndex=e.lastIndex,t},Qn=te?te.prototype:void 0,Mn=Qn?Qn.valueOf:void 0;var Dn=function(e){return Mn?Object(Mn.call(e)):{}};var Bn=function(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)};var Ln=function(e,t,r){var n=e.constructor;switch(t){case"[object ArrayBuffer]":return Nn(e);case"[object Boolean]":case"[object Date]":return new n(+e);case"[object DataView]":return Cn(e,r);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return Bn(e,r);case"[object Map]":return new n;case"[object Number]":case"[object String]":return new n(e);case"[object RegExp]":return Hn(e);case"[object Set]":return new n;case"[object Symbol]":return Dn(e)}},kn=Object.create,Un=function(){function r(){}return function(e){if(!le(e))return{};if(kn)return kn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}}();var Vn=function(e){return"function"!=typeof e.constructor||Mt(e)?{}:Un(Pn(e))};var qn=function(e){return gt(e)&&"[object Map]"==cr(e)},Wn=At&&At.isMap,zn=Wn?Tt(Wn):qn;var $n=function(e){return gt(e)&&"[object Set]"==cr(e)},Jn=At&&At.isSet,Yn=Jn?Tt(Jn):$n,Gn=1,Kn=2,Zn=4,Xn="[object Arguments]",ei="[object Function]",ti="[object GeneratorFunction]",ri="[object Object]",ni={};ni[Xn]=ni["[object Array]"]=ni["[object ArrayBuffer]"]=ni["[object DataView]"]=ni["[object Boolean]"]=ni["[object Date]"]=ni["[object Float32Array]"]=ni["[object Float64Array]"]=ni["[object Int8Array]"]=ni["[object Int16Array]"]=ni["[object Int32Array]"]=ni["[object Map]"]=ni["[object Number]"]=ni[ri]=ni["[object RegExp]"]=ni["[object Set]"]=ni["[object String]"]=ni["[object Symbol]"]=ni["[object Uint8Array]"]=ni["[object Uint8ClampedArray]"]=ni["[object Uint16Array]"]=ni["[object Uint32Array]"]=!0,ni["[object Error]"]=ni[ei]=ni["[object WeakMap]"]=!1;var ii=function r(n,i,a,e,t,o){var s,c=i&Gn,u=i&Kn,f=i&Zn;if(a&&(s=t?a(n,e,t,o):a(n)),void 0!==s)return s;if(!le(n))return n;var l=ut(n);if(l){if(s=An(n),!c)return jn(n,s)}else{var h=cr(n),d=h==ei||h==ti;if(jt(n))return _n(n,c);if(h==ri||h==Xn||d&&!t){if(s=u||d?{}:Vn(n),!c)return u?On(n,Fn(s,n)):wn(n,gn(s,n))}else{if(!ni[h])return t?n:{};s=Ln(n,h,c)}}o||(o=new Ye);var p=o.get(n);if(p)return p;if(o.set(n,s),Yn(n))return n.forEach(function(e){s.add(r(e,i,a,e,n,o))}),s;if(zn(n))return n.forEach(function(e,t){s.set(t,r(e,i,a,t,n,o))}),s;var v=f?u?En:qt:u?keysIn:Vt,m=l?void 0:v(n);return ln(m||n,function(e,t){m&&(e=n[t=e]),vn(s,t,r(e,i,a,t,n,o))}),s};var ai=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0};var oi=function(e,t,r){var n=-1,i=e.length;t<0&&(t=i<-t?0:i+t),(r=i<r?i:r)<0&&(r+=i),i=r<t?0:r-t>>>0,t>>>=0;for(var a=Array(i);++n<i;)a[n]=e[n+t];return a};var si=function(e,t){return t.length<2?e:Dr(e,oi(t,0,-1))};var ci=function(e,t){return t=Qr(t,e),null==(e=si(e,t))||delete e[Mr(ai(t))]},ui=Function.prototype,fi=Object.prototype,li=ui.toString,hi=fi.hasOwnProperty,di=li.call(Object);var pi=function(e){if(!gt(e)||"[object Object]"!=fe(e))return!1;var t=Pn(e);if(null===t)return!0;var r=hi.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&li.call(r)==di};var vi=function(e){return pi(e)?void 0:e},mi=te?te.isConcatSpreadable:void 0;var gi=function(e){return ut(e)||Ft(e)||!!(mi&&e&&e[mi])};var yi=function e(t,r,n,i,a){var o=-1,s=t.length;for(n||(n=gi),a||(a=[]);++o<s;){var c=t[o];0<r&&n(c)?1<r?e(c,r-1,n,i,a):ct(a,c):i||(a[a.length]=c)}return a};var bi=function(e){return null!=e&&e.length?yi(e,1):[]};var Ri=function(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)},xi=Math.max;var Fi=function(a,o,s){return o=xi(void 0===o?a.length-1:o,0),function(){for(var e=arguments,t=-1,r=xi(e.length-o,0),n=Array(r);++t<r;)n[t]=e[o+t];t=-1;for(var i=Array(o+1);++t<o;)i[t]=e[t];return i[o]=s(n),Ri(a,this,i)}};var _i=function(e){return function(){return e}},ji=hn?function(e,t){return hn(e,"toString",{configurable:!0,enumerable:!1,value:_i(t),writable:!0})}:qr,wi=Date.now;var Pi=function(r){var n=0,i=0;return function(){var e=wi(),t=16-(e-i);if(i=e,0<t){if(800<=++n)return arguments[0]}else n=0;return r.apply(void 0,arguments)}},Si=Pi(ji);var Oi=function(e){return Si(Fi(e,void 0,bi),e+"")},Ei=Oi(function(t,e){var r={};if(null==t)return r;var n=!1;e=Tr(e,function(e){return e=Qr(e,t),n||(n=1<e.length),e}),mn(t,En(t),r),n&&(r=ii(r,7,vi));for(var i=e.length;i--;)ci(r,e[i]);return r});var Ti=function(e){return e!=e};var Ai=function(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1};var Ni=function(e,t,r){return t==t?Ai(e,t,r):Gr(e,Ti,r)};var Ci=function(e,t){return!(null==e||!e.length)&&-1<Ni(e,t,0)};var Ii=function(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1},Hi=Math.min;var Qi=function(e,t,r){for(var n=r?Ii:Ci,i=e[0].length,a=e.length,o=a,s=Array(a),c=1/0,u=[];o--;){var f=e[o];o&&t&&(f=Tr(f,Tt(t))),c=Hi(f.length,c),s[o]=!r&&(t||120<=i&&120<=f.length)?new Ze(o&&f):void 0}f=e[0];var l=-1,h=s[0];e:for(;++l<i&&u.length<c;){var d=f[l],p=t?t(d):d;if(d=r||0!==d?d:0,!(h?et(h,p):n(u,p,r))){for(o=a;--o;){var v=s[o];if(!(v?et(v,p):n(e[o],p,r)))continue e}h&&h.push(p),u.push(d)}}return u};var Mi=function(e,t){return Si(Fi(e,t,qr),e+"")};var Di=function(e){return gt(e)&&Ut(e)};var Bi=function(e){return Di(e)?e:[]},Li=Mi(function(e){var t=Tr(e,Bi);return t.length&&t[0]===e[0]?Qi(t):[]});var ki=function(c){return function(e,t,r){for(var n=-1,i=Object(e),a=r(e),o=a.length;o--;){var s=a[c?o:++n];if(!1===t(i[s],s,i))break}return e}}();var Ui=function(e,t){return e&&ki(e,t,Vt)};var Vi=function(e){return"function"==typeof e?e:qr};var qi=function(e,t){return e&&Ui(e,Vi(t))};var Wi=function(a,o){return function(e,t){if(null==e)return e;if(!Ut(e))return a(e,t);for(var r=e.length,n=o?r:-1,i=Object(e);(o?n--:++n<r)&&!1!==t(i[n],n,i););return e}}(Ui);var zi=function(e,t){return(ut(e)?ln:Wi)(e,Vi(t))};var $i=function(e,n){var i=[];return Wi(e,function(e,t,r){n(e,t,r)&&i.push(e)}),i};var Ji=function(e,t){return(ut(e)?lt:$i)(e,Jr(t,3))};var Yi=function(e,n){var i=-1,a=Ut(e)?Array(e.length):[];return Wi(e,function(e,t,r){a[++i]=n(e,t,r)}),a};var Gi=function(e,t){return(ut(e)?Tr:Yi)(e,Jr(t,3))};var Ki=function(e,t,r,n){var i=-1,a=null==e?0:e.length;for(n&&a&&(r=e[++i]);++i<a;)r=t(r,e[i],i,e);return r};var Zi=function(e,n,i,a,t){return t(e,function(e,t,r){i=a?(a=!1,e):n(i,e,t,r)}),i};var Xi=function(e,t,r){var n=ut(e)?Ki:Zi,i=arguments.length<3;return n(e,Jr(t,4),r,i,Wi)},ea=Math.max;var ta=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:an(r);return i<0&&(i=ea(n+i,0)),Ni(e,t,i)};var ra=function(e){return"number"==typeof e||gt(e)&&"[object Number]"==fe(e)};var na=function(e){return ra(e)&&e!=+e};var ia=function(e,t){return pr(e,t)};var aa=function(e){return void 0===e};var oa=function(e){return"string"==typeof e||!ut(e)&>(e)&&"[object String]"==fe(e)};var sa=function(e,t,r){var n=e.length;return r=void 0===r?n:r,!t&&n<=r?e:oi(e,t,r)};var ca=function(e,t){for(var r=e.length;r--&&-1<Ni(t,e[r],0););return r};var ua=function(e,t){for(var r=-1,n=e.length;++r<n&&-1<Ni(t,e[r],0););return r};var fa=function(e){return e.split("")},la=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");var ha=function(e){return la.test(e)},da="\\ud800-\\udfff",pa="["+da+"]",va="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",ma="\\ud83c[\\udffb-\\udfff]",ga="[^"+da+"]",ya="(?:\\ud83c[\\udde6-\\uddff]){2}",ba="[\\ud800-\\udbff][\\udc00-\\udfff]",Ra="(?:"+va+"|"+ma+")"+"?",xa="[\\ufe0e\\ufe0f]?",Fa=xa+Ra+("(?:\\u200d(?:"+[ga,ya,ba].join("|")+")"+xa+Ra+")*"),_a="(?:"+[ga+va+"?",va,ya,ba,pa].join("|")+")",ja=RegExp(ma+"(?="+ma+")|"+_a+Fa,"g");var wa=function(e){return e.match(ja)||[]};var Pa=function(e){return ha(e)?wa(e):fa(e)},Sa=/^\s+|\s+$/g;var Oa=function(e,t,r){if((e=Hr(e))&&(r||void 0===t))return e.replace(Sa,"");if(!e||!(t=Ir(t)))return e;var n=Pa(e),i=Pa(t),a=ua(n,i),o=ca(n,i)+1;return sa(n,a,o).join("")};var Ea=function(e,t,r){if(!le(r))return!1;var n=typeof t;return!!("number"==n?Ut(r)&&Pt(t,r.length):"string"==n&&t in r)&&B(r[t],e)},Ta=Object.prototype,Aa=Ta.hasOwnProperty,Na=Mi(function(e,t){e=Object(e);var r=-1,n=t.length,i=2<n?t[2]:void 0;for(i&&Ea(t[0],t[1],i)&&(n=1);++r<n;)for(var a=t[r],o=xn(a),s=-1,c=o.length;++s<c;){var u=o[s],f=e[u];(void 0===f||B(f,Ta[u])&&!Aa.call(e,u))&&(e[u]=a[u])}return e});var Ca=function(e,t,r){(void 0===r||B(e[t],r))&&(void 0!==r||t in e)||dn(e,t,r)};var Ia=function(e,t){return"__proto__"==t?void 0:e[t]};var Ha=function(e){return mn(e,xn(e))};var Qa=function(e,t,r,n,i,a,o){var s=Ia(e,r),c=Ia(t,r),u=o.get(c);if(u)Ca(e,r,u);else{var f=a?a(s,c,r+"",e,t,o):void 0,l=void 0===f;if(l){var h=ut(c),d=!h&&jt(c),p=!h&&!d&&Ct(c);f=c,h||d||p?f=ut(s)?s:Di(s)?jn(s):d?_n(c,!(l=!1)):p?Bn(c,!(l=!1)):[]:pi(c)||Ft(c)?Ft(f=s)?f=Ha(s):(!le(s)||n&&de(s))&&(f=Vn(c)):l=!1}l&&(o.set(c,f),i(f,c,n,a,o),o.delete(c)),Ca(e,r,f)}};var Ma=function n(i,a,o,s,c){i!==a&&ki(a,function(e,t){if(le(e))c||(c=new Ye),Qa(i,a,t,o,n,s,c);else{var r=s?s(Ia(i,t),e,t+"",i,a,c):void 0;void 0===r&&(r=e),Ca(i,t,r)}},xn)};var Da=function(s){return Mi(function(e,t){var r=-1,n=t.length,i=1<n?t[n-1]:void 0,a=2<n?t[2]:void 0;for(i=3<s.length&&"function"==typeof i?(n--,i):void 0,a&&Ea(t[0],t[1],a)&&(i=n<3?void 0:i,n=1),e=Object(e);++r<n;){var o=t[r];o&&s(e,o,r,i)}return e})}(function(e,t,r){Ma(e,t,r)});var Ba=function e(t){if(ra(t))return t;if(oa(t))return parseFloat(t);if(Array.isArray(t))return Gi(t,e);throw new Error("The value should be a number, a parseable string or an array of those.")};var La=function(r,e){var n={},t=Ji(e,function(e){return-1!==e.indexOf("attribute:")}),i=Gi(t,function(e){return e.split(":")[1]});-1===ta(i,"*")?zi(i,function(e){r.isConjunctiveFacet(e)&&r.isFacetRefined(e)&&(n.facetsRefinements||(n.facetsRefinements={}),n.facetsRefinements[e]=r.facetsRefinements[e]),r.isDisjunctiveFacet(e)&&r.isDisjunctiveFacetRefined(e)&&(n.disjunctiveFacetsRefinements||(n.disjunctiveFacetsRefinements={}),n.disjunctiveFacetsRefinements[e]=r.disjunctiveFacetsRefinements[e]),r.isHierarchicalFacet(e)&&r.isHierarchicalFacetRefined(e)&&(n.hierarchicalFacetsRefinements||(n.hierarchicalFacetsRefinements={}),n.hierarchicalFacetsRefinements[e]=r.hierarchicalFacetsRefinements[e]);var t=r.getNumericRefinements(e);fn(t)||(n.numericRefinements||(n.numericRefinements={}),n.numericRefinements[e]=r.numericRefinements[e])}):(fn(r.numericRefinements)||(n.numericRefinements=r.numericRefinements),fn(r.facetsRefinements)||(n.facetsRefinements=r.facetsRefinements),fn(r.disjunctiveFacetsRefinements)||(n.disjunctiveFacetsRefinements=r.disjunctiveFacetsRefinements),fn(r.hierarchicalFacetsRefinements)||(n.hierarchicalFacetsRefinements=r.hierarchicalFacetsRefinements));var a=Ji(e,function(e){return-1===e.indexOf("attribute:")});return zi(a,function(e){n[e]=r[e]}),n},ka={addRefinement:function(e,t,r){if(ka.isRefined(e,t,r))return e;var n=""+r,i=e[t]?e[t].concat(n):[n],a={};return a[t]=i,Na({},a,e)},removeRefinement:function(e,r,t){if(aa(t))return ka.clearRefinement(e,r);var n=""+t;return ka.clearRefinement(e,function(e,t){return r===t&&n===e})},toggleRefinement:function(e,t,r){if(aa(r))throw new Error("toggleRefinement should be used with a value");return ka.isRefined(e,t,r)?ka.removeRefinement(e,t,r):ka.addRefinement(e,t,r)},clearRefinement:function(e,i,a){if(aa(i))return fn(e)?e:{};if(oa(i))return fn(e[i])?e:Ei(e,i);if(de(i)){var o=!1,t=Xi(e,function(e,t,r){var n=Ji(t,function(e){return!i(e,r,a)});return fn(n)?o=!0:(n.length!==t.length&&(o=!0),e[r]=n),e},{});return o?t:e}},isRefined:function(e,t,r){var n=ta,i=!!e[t]&&0<e[t].length;if(aa(r)||!i)return i;var a=""+r;return-1!==n(e[t],a)}},Ua=ka;function Va(e){var t=e?Va._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.optionalTagFilters=t.optionalTagFilters,this.optionalFacetFilters=t.optionalFacetFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.minProximity=t.minProximity,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.snippetEllipsisText=t.snippetEllipsisText,this.disableExactOnAttributes=t.disableExactOnAttributes,this.enableExactOnSingleWordQuery=t.enableExactOnSingleWordQuery,this.offset=t.offset,this.length=t.length;var r=this;qi(t,function(e,t){-1===Va.PARAMETERS.indexOf(t)&&(r[t]=e)})}Va.PARAMETERS=Vt(new Va),Va._parseNumbers=function(n){if(n instanceof Va)return n;var i={};if(zi(["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"],function(e){var t=n[e];if(oa(t)){var r=parseFloat(t);i[e]=na(r)?t:r}}),Array.isArray(n.insideBoundingBox)&&(i.insideBoundingBox=n.insideBoundingBox.map(function(e){return e.map(function(e){return parseFloat(e)})})),n.numericRefinements){var a={};zi(n.numericRefinements,function(e,n){a[n]={},zi(e,function(e,t){var r=Gi(e,function(e){return Array.isArray(e)?Gi(e,function(e){return oa(e)?parseFloat(e):e}):oa(e)?parseFloat(e):e});a[n][t]=r})}),i.numericRefinements=a}return Da({},n,i)},Va.make=function(e){var r=new Va(e);return zi(e.hierarchicalFacets,function(e){if(e.rootPath){var t=r.getHierarchicalRefinement(e.name);0<t.length&&0!==t[0].indexOf(e.rootPath)&&(r=r.clearRefinements(e.name)),0===(t=r.getHierarchicalRefinement(e.name)).length&&(r=r.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}}),r},Va.validate=function(e,t){var r=t||{};return e.tagFilters&&r.tagRefinements&&0<r.tagRefinements.length?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."):0<e.tagRefinements.length&&r.tagFilters?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."):e.numericFilters&&r.numericRefinements&&!fn(r.numericRefinements)?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."):!fn(e.numericRefinements)&&r.numericFilters?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."):null},Va.prototype={constructor:Va,clearRefinements:function(e){var t=Ua.clearRefinement,r={numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")};return r.numericRefinements===this.numericRefinements&&r.facetsRefinements===this.facetsRefinements&&r.facetsExcludes===this.facetsExcludes&&r.disjunctiveFacetsRefinements===this.disjunctiveFacetsRefinements&&r.hierarchicalFacetsRefinements===this.hierarchicalFacetsRefinements?this:this.setQueryParameters(r)},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e})},addNumericRefinement:function(e,t,r){var n=Ba(r);if(this.isNumericRefined(e,t,n))return this;var i=Da({},this.numericRefinements);return i[e]=Da({},i[e]),i[e][t]?(i[e][t]=i[e][t].slice(),i[e][t].push(n)):i[e][t]=[n],this.setQueryParameters({numericRefinements:i})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(r,n,e){if(void 0===e)return void 0!==n?this.isNumericRefined(r,n)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(e,t){return t===r&&e.op===n})}):this:this.isNumericRefined(r)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(e,t){return t===r})}):this;var i=Ba(e);return this.isNumericRefined(r,n,i)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(e,t){return t===r&&e.op===n&&ia(e.val,i)})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(a){if(aa(a))return fn(this.numericRefinements)?this.numericRefinements:{};if(oa(a))return fn(this.numericRefinements[a])?this.numericRefinements:Ei(this.numericRefinements,a);if(de(a)){var o=!1,e=Xi(this.numericRefinements,function(e,t,n){var i={};return zi(t,function(e,t){var r=[];zi(e,function(e){a({val:e,op:t},n,"numeric")||r.push(e)}),fn(r)?o=!0:(r.length!==e.length&&(o=!0),i[t]=r)}),fn(i)||(e[n]=i),e},{});return o?e:this.numericRefinements}},addFacet:function(e){return this.isConjunctiveFacet(e)?this:this.setQueryParameters({facets:this.facets.concat([e])})},addDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this:this.setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.concat([e])})},addHierarchicalFacet:function(e){if(this.isHierarchicalFacet(e.name))throw new Error("Cannot declare two hierarchical facets with the same name: `"+e.name+"`");return this.setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.concat([e])})},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({facetsRefinements:Ua.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({facetsExcludes:Ua.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return Ua.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({disjunctiveFacetsRefinements:Ua.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacet:function(t){return this.isConjunctiveFacet(t)?this.clearRefinements(t).setQueryParameters({facets:Ji(this.facets,function(e){return e!==t})}):this},removeDisjunctiveFacet:function(t){return this.isDisjunctiveFacet(t)?this.clearRefinements(t).setQueryParameters({disjunctiveFacets:Ji(this.disjunctiveFacets,function(e){return e!==t})}):this},removeHierarchicalFacet:function(t){return this.isHierarchicalFacet(t)?this.clearRefinements(t).setQueryParameters({hierarchicalFacets:Ji(this.hierarchicalFacets,function(e){return e.name!==t})}):this},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({facetsRefinements:Ua.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({facetsExcludes:Ua.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return Ua.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({disjunctiveFacetsRefinements:Ua.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(t){if(!this.isTagRefined(t))return this;var e={tagRefinements:Ji(this.tagRefinements,function(e){return e!==t})};return this.setQueryParameters(e)},toggleRefinement:function(e,t){return this.toggleFacetRefinement(e,t)},toggleFacetRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleConjunctiveFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleConjunctiveFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsRefinements:Ua.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsExcludes:Ua.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({disjunctiveFacetsRefinements:Ua.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),n={};return void 0!==this.hierarchicalFacetsRefinements[e]&&0<this.hierarchicalFacetsRefinements[e].length&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+r))?-1===t.indexOf(r)?n[e]=[]:n[e]=[t.slice(0,t.lastIndexOf(r))]:n[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:Na({},n,this.hierarchicalFacetsRefinements)})},addHierarchicalFacetRefinement:function(e,t){if(this.isHierarchicalFacetRefined(e))throw new Error(e+" is already refined.");var r={};return r[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:Na({},r,this.hierarchicalFacetsRefinements)})},removeHierarchicalFacetRefinement:function(e){if(!this.isHierarchicalFacetRefined(e))throw new Error(e+" is not refined.");var t={};return t[e]=[],this.setQueryParameters({hierarchicalFacetsRefinements:Na({},t,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return-1<ta(this.disjunctiveFacets,e)},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return-1<ta(this.facets,e)},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return Ua.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return Ua.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this.getHierarchicalRefinement(e);return t?-1!==ta(r,t):0<r.length},isNumericRefined:function(e,t,r){if(aa(r)&&aa(t))return!!this.numericRefinements[e];var n=this.numericRefinements[e]&&!aa(this.numericRefinements[e][t]);if(aa(r)||!n)return n;var i,a,o=Ba(r),s=!aa((i=this.numericRefinements[e][t],a=o,cn(i,function(e){return ia(e,a)})));return n&&s},isTagRefined:function(e){return-1!==ta(this.tagRefinements,e)},getRefinedDisjunctiveFacets:function(){var e=Li(Vt(this.numericRefinements),this.disjunctiveFacets);return Vt(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return Li(Gi(this.hierarchicalFacets,"name"),Vt(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var t=this.getRefinedDisjunctiveFacets();return Ji(this.disjunctiveFacets,function(e){return-1===ta(t,e)})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var r=this.managedParameters,n={};return qi(this,function(e,t){-1===ta(r,t)&&void 0!==e&&(n[t]=e)}),n},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var r={};return r[e]=t,this.setQueryParameters(r)},setQueryParameters:function(r){if(!r)return this;var e=Va.validate(this,r);if(e)throw e;var n=Va._parseNumbers(r);return this.mutateMe(function(t){var e=Vt(r);return zi(e,function(e){t[e]=n[e]}),t})},filter:function(e){return La(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),t},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"!=typeof e.showParentLevel||e.showParentLevel},getHierarchicalFacetByName:function(e){return cn(this.hierarchicalFacets,{name:e})},getHierarchicalFacetBreadcrumb:function(e){if(!this.isHierarchicalFacet(e))throw new Error("Cannot get the breadcrumb of an unknown hierarchical facet: `"+e+"`");var t=this.getHierarchicalRefinement(e)[0];if(!t)return[];var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),n=t.split(r);return Gi(n,Oa)},toString:function(){return JSON.stringify(this,null,2)}};var qa=Va;var Wa=function(e){for(var t=-1,r=null==e?0:e.length,n=0,i=[];++t<r;){var a=e[t];a&&(i[n++]=a)}return i};var za=function(e,t){for(var r,n=-1,i=e.length;++n<i;){var a=t(e[n]);void 0!==a&&(r=void 0===r?a:r+a)}return r};var $a=function(e,t){return e&&e.length?za(e,Jr(t,2)):0};var Ja=function(t,e){return Tr(e,function(e){return t[e]})};var Ya=function(e){return null==e?[]:Ja(e,Vt(e))},Ga=Math.max;var Ka=function(e,t,r,n){e=Ut(e)?e:Ya(e),r=r&&!n?an(r):0;var i=e.length;return r<0&&(r=Ga(i+r,0)),oa(e)?r<=i&&-1<e.indexOf(t,r):!!i&&-1<Ni(e,t,r)};var Za=function(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e};var Xa=function(e,t){if(e!==t){var r=void 0!==e,n=null===e,i=e==e,a=Rr(e),o=void 0!==t,s=null===t,c=t==t,u=Rr(t);if(!s&&!u&&!a&&t<e||a&&o&&c&&!s&&!u||n&&o&&c||!r&&c||!i)return 1;if(!n&&!a&&!u&&e<t||u&&r&&i&&!n&&!a||s&&r&&i||!o&&i||!c)return-1}return 0};var eo=function(e,t,r){for(var n=-1,i=e.criteria,a=t.criteria,o=i.length,s=r.length;++n<o;){var c=Xa(i[n],a[n]);if(c)return s<=n?c:c*("desc"==r[n]?-1:1)}return e.index-t.index};var to=function(e,n,r){var i=-1;n=Tr(n.length?n:[qr],Tt(Jr));var t=Yi(e,function(t,e,r){return{criteria:Tr(n,function(e){return e(t)}),index:++i,value:t}});return Za(t,function(e,t){return eo(e,t,r)})};var ro=function(e,t,r,n){return null==e?[]:(ut(t)||(t=null==t?[]:[t]),ut(r=n?void 0:r)||(r=null==r?[]:[r]),to(e,t,r))},no=Gt&&new Gt,io=no?function(e,t){return no.set(e,t),e}:qr;var ao=function(n){return function(){var e=arguments;switch(e.length){case 0:return new n;case 1:return new n(e[0]);case 2:return new n(e[0],e[1]);case 3:return new n(e[0],e[1],e[2]);case 4:return new n(e[0],e[1],e[2],e[3]);case 5:return new n(e[0],e[1],e[2],e[3],e[4]);case 6:return new n(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new n(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var t=Un(n.prototype),r=n.apply(t,e);return le(r)?r:t}};var oo=function(t,e,r){var n=1&e,i=ao(t);return function e(){return(this&&this!==ee&&this instanceof e?i:t).apply(n?r:this,arguments)}},so=Math.max;var co=function(e,t,r,n){for(var i=-1,a=e.length,o=r.length,s=-1,c=t.length,u=so(a-o,0),f=Array(c+u),l=!n;++s<c;)f[s]=t[s];for(;++i<o;)(l||i<a)&&(f[r[i]]=e[i]);for(;u--;)f[s++]=e[i++];return f},uo=Math.max;var fo=function(e,t,r,n){for(var i=-1,a=e.length,o=-1,s=r.length,c=-1,u=t.length,f=uo(a-s,0),l=Array(f+u),h=!n;++i<f;)l[i]=e[i];for(var d=i;++c<u;)l[d+c]=t[c];for(;++o<s;)(h||i<a)&&(l[d+r[o]]=e[i++]);return l};var lo=function(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n};var ho=function(){};function po(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}var vo=(po.prototype=Un(ho.prototype)).constructor=po;var mo=no?function(e){return no.get(e)}:function(){},go={},yo=Object.prototype.hasOwnProperty;var bo=function(e){for(var t=e.name+"",r=go[t],n=yo.call(go,t)?r.length:0;n--;){var i=r[n],a=i.func;if(null==a||a==e)return i.name}return t};function Ro(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}var xo=(Ro.prototype=Un(ho.prototype)).constructor=Ro;var Fo=function(e){if(e instanceof vo)return e.clone();var t=new xo(e.__wrapped__,e.__chain__);return t.__actions__=jn(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t},_o=Object.prototype.hasOwnProperty;function jo(e){if(gt(e)&&!ut(e)&&!(e instanceof vo)){if(e instanceof xo)return e;if(_o.call(e,"__wrapped__"))return Fo(e)}return new xo(e)}var wo=(jo.prototype=ho.prototype).constructor=jo;var Po=function(e){var t=bo(e),r=wo[t];if("function"!=typeof r||!(t in vo.prototype))return!1;if(e===r)return!0;var n=mo(r);return!!n&&e===n[0]},So=Pi(io),Oo=/\{\n\/\* \[wrapped with (.+)\] \*/,Eo=/,? & /;var To=function(e){var t=e.match(Oo);return t?t[1].split(Eo):[]},Ao=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;var No=function(e,t){var r=t.length;if(!r)return e;var n=r-1;return t[n]=(1<r?"& ":"")+t[n],t=t.join(2<r?", ":" "),e.replace(Ao,"{\n/* [wrapped with "+t+"] */\n")},Co=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];var Io=function(r,n){return ln(Co,function(e){var t="_."+e[0];n&e[1]&&!Ci(r,t)&&r.push(t)}),r.sort()};var Ho=function(e,t,r){var n=t+"";return Si(e,No(n,Io(To(n),r)))};var Qo=function(e,t,r,n,i,a,o,s,c,u){var f=8&t;t|=f?32:64,4&(t&=~(f?64:32))||(t&=-4);var l=[e,t,i,f?a:void 0,f?o:void 0,f?void 0:a,f?void 0:o,s,c,u],h=r.apply(void 0,l);return Po(e)&&So(h,l),h.placeholder=n,Ho(h,e,t)};var Mo=function(e){return e.placeholder},Do=Math.min;var Bo=function(e,t){for(var r=e.length,n=Do(t.length,r),i=jn(e);n--;){var a=t[n];e[n]=Pt(a,r)?i[a]:void 0}return e},Lo="__lodash_placeholder__";var ko=function(e,t){for(var r=-1,n=e.length,i=0,a=[];++r<n;){var o=e[r];o!==t&&o!==Lo||(e[r]=Lo,a[i++]=r)}return a},Uo=1,Vo=2,qo=8,Wo=16,zo=128,$o=512;function Jo(u,f,l,h,d,p,v,m,g,y){var b=f&zo,R=f&Uo,x=f&Vo,F=f&(qo|Wo),_=f&$o,j=x?void 0:ao(u);return function e(){for(var t=arguments.length,r=Array(t),n=t;n--;)r[n]=arguments[n];if(F)var i=Mo(e),a=lo(r,i);if(h&&(r=co(r,h,d,F)),p&&(r=fo(r,p,v,F)),t-=a,F&&t<y){var o=ko(r,i);return Qo(u,f,Jo,e.placeholder,l,r,o,m,g,y-t)}var s=R?l:this,c=x?s[u]:u;return t=r.length,m?r=Bo(r,m):_&&1<t&&r.reverse(),b&&g<t&&(r.length=g),this&&this!==ee&&this instanceof e&&(c=j||ao(c)),c.apply(s,r)}}var Yo=Jo;var Go=function(o,s,c){var u=ao(o);return function e(){for(var t=arguments.length,r=Array(t),n=t,i=Mo(e);n--;)r[n]=arguments[n];var a=t<3&&r[0]!==i&&r[t-1]!==i?[]:ko(r,i);return(t-=a.length)<c?Qo(o,s,Yo,e.placeholder,void 0,r,a,void 0,void 0,c-t):Ri(this&&this!==ee&&this instanceof e?u:o,this,r)}};var Ko=function(s,e,c,u){var f=1&e,l=ao(s);return function e(){for(var t=-1,r=arguments.length,n=-1,i=u.length,a=Array(i+r),o=this&&this!==ee&&this instanceof e?l:s;++n<i;)a[n]=u[n];for(;r--;)a[n++]=arguments[++t];return Ri(o,f?c:this,a)}},Zo="__lodash_placeholder__",Xo=Math.min;var es=function(e,t){var r=e[1],n=t[1],i=r|n,a=i<131,o=128==n&&8==r||128==n&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!a&&!o)return e;1&n&&(e[2]=t[2],i|=1&r?0:4);var s=t[3];if(s){var c=e[3];e[3]=c?co(c,s,t[4]):s,e[4]=c?ko(e[3],Zo):t[4]}return(s=t[5])&&(c=e[5],e[5]=c?fo(c,s,t[6]):s,e[6]=c?ko(e[5],Zo):t[6]),(s=t[7])&&(e[7]=s),128&n&&(e[8]=null==e[8]?t[8]:Xo(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=i,e},ts=Math.max;var rs=function(e,t,r,n,i,a,o,s){var c=2&t;if(!c&&"function"!=typeof e)throw new TypeError("Expected a function");var u=n?n.length:0;if(u||(t&=-97,n=i=void 0),o=void 0===o?o:ts(an(o),0),s=void 0===s?s:an(s),u-=i?i.length:0,64&t){var f=n,l=i;n=i=void 0}var h=c?void 0:mo(e),d=[e,t,r,n,i,f,l,a,o,s];if(h&&es(d,h),e=d[0],t=d[1],r=d[2],n=d[3],i=d[4],!(s=d[9]=void 0===d[9]?c?0:e.length:ts(d[9]-u,0))&&24&t&&(t&=-25),t&&1!=t)p=8==t||16==t?Go(e,t,s):32!=t&&33!=t||i.length?Yo.apply(void 0,d):Ko(e,t,r,n);else var p=oo(e,t,r);return Ho((h?io:So)(p,d),e,t)},ns=Mi(function(e,t){var r=ko(t,Mo(ns));return rs(e,32,void 0,t,r)});ns.placeholder={};var is=ns,as=Mi(function(e,t){var r=ko(t,Mo(as));return rs(e,64,void 0,t,r)});as.placeholder={};var os=as;var ss=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=t<=e?e:t)),e};var cs=function(e,t,r){return e=Hr(e),r=null==r?0:ss(an(r),0,e.length),t=Ir(t),e.slice(r,r+t.length)==t},us=function(e,i){return Xi(e,function(e,t){var r=t.split(":");if(i&&1===r.length){var n=cn(i,function(e){return cs(e,t[0])});n&&(r=n.split(":"))}return e[0].push(r[0]),e[1].push(r[1]),e},[[],[]])};var fs=function(e,t,r,n){if(!le(e))return e;for(var i=-1,a=(t=Qr(t,e)).length,o=a-1,s=e;null!=s&&++i<a;){var c=Mr(t[i]),u=r;if(i!=o){var f=s[c];void 0===(u=n?n(f,c,s):void 0)&&(u=le(f)?f:Pt(t[i+1])?[]:{})}vn(s,c,u),s=s[c]}return e};var ls=function(e,t,r){for(var n=-1,i=t.length,a={};++n<i;){var o=t[n],s=Dr(e,o);r(s,o)&&fs(a,Qr(o,e),s)}return a};var hs=function(e,r){if(null==e)return{};var t=Tr(En(e),function(e){return[e]});return r=Jr(r),ls(e,t,function(e,t){return r(e,t[0])})},ds=function(f){return function(e,t){var d,p,v,m,g,r=f.hierarchicalFacets[t],n=f.hierarchicalFacetsRefinements[r.name]&&f.hierarchicalFacetsRefinements[r.name][0]||"",i=f._getHierarchicalFacetSeparator(r),a=f._getHierarchicalRootPath(r),o=f._getHierarchicalShowParentLevel(r),s=us(f._getHierarchicalFacetSortBy(r)),c=(d=s,p=i,v=a,m=o,g=n,function(e,t,r){var n,i,a,o,s,c,u,f=e;if(0<r){var l=0;for(f=e;l<r;)f=f&&cn(f.data,{isRefined:!0}),l++}if(f){var h=(a=f.path||v,o=g,s=p,c=v,u=m,function(e,t){return(!c||0===t.indexOf(c)&&c!==t)&&(!c&&-1===t.indexOf(s)||c&&t.split(s).length-c.split(s).length==1||-1===t.indexOf(s)&&-1===o.indexOf(s)||0===o.indexOf(t)||0===t.indexOf(a+s)&&(u||0===t.indexOf(o)))});f.data=ro(Gi(hs(t.data,h),(n=p,i=g,function(e,t){return{name:Oa(ai(t.split(n))),path:t,count:e,isRefined:i===t||0===i.indexOf(t+n),data:null}})),d[0],d[1])}return e}),u=e;return a&&(u=e.slice(a.split(i).length)),Xi(u,c,{name:f.hierarchicalFacets[t].name,count:null,isRefined:!0,path:null,data:null})}};function ps(e){var r={};return zi(e,function(e,t){r[e]=t}),r}function vs(e,t,r){t&&t[r]&&(e.stats=t[r])}function ms(f,r){var l=r[0];this._rawResults=r,this.query=l.query,this.parsedQuery=l.parsedQuery,this.hits=l.hits,this.index=l.index,this.hitsPerPage=l.hitsPerPage,this.nbHits=l.nbHits,this.nbPages=l.nbPages,this.page=l.page,this.processingTimeMS=$a(r,"processingTimeMS"),this.aroundLatLng=l.aroundLatLng,this.automaticRadius=l.automaticRadius,this.serverUsed=l.serverUsed,this.timeoutCounts=l.timeoutCounts,this.timeoutHits=l.timeoutHits,this.exhaustiveFacetsCount=l.exhaustiveFacetsCount,this.exhaustiveNbHits=l.exhaustiveNbHits,this.userData=l.userData,this.queryID=l.queryID,this.disjunctiveFacets=[],this.hierarchicalFacets=Gi(f.hierarchicalFacets,function(){return[]}),this.facets=[];var e=f.getRefinedDisjunctiveFacets(),h=ps(f.facets),d=ps(f.disjunctiveFacets),n=1,p=this;zi(l.facets,function(e,t){var r,n,i=(r=f.hierarchicalFacets,n=t,cn(r,function(e){return Ka(e.attributes,n)}));if(i){var a=i.attributes.indexOf(t),o=sn(f.hierarchicalFacets,{name:i.name});p.hierarchicalFacets[o][a]={attribute:t,data:e,exhaustive:l.exhaustiveFacetsCount}}else{var s,c=-1!==ta(f.disjunctiveFacets,t),u=-1!==ta(f.facets,t);c&&(s=d[t],p.disjunctiveFacets[s]={name:t,data:e,exhaustive:l.exhaustiveFacetsCount},vs(p.disjunctiveFacets[s],l.facets_stats,t)),u&&(s=h[t],p.facets[s]={name:t,data:e,exhaustive:l.exhaustiveFacetsCount},vs(p.facets[s],l.facets_stats,t))}}),this.hierarchicalFacets=Wa(this.hierarchicalFacets),zi(e,function(e){var a=r[n],o=f.getHierarchicalFacetByName(e);zi(a.facets,function(e,t){var r;if(o){r=sn(f.hierarchicalFacets,{name:o.name});var n=sn(p.hierarchicalFacets[r],{attribute:t});if(-1===n)return;p.hierarchicalFacets[r][n].data=Da({},p.hierarchicalFacets[r][n].data,e)}else{r=d[t];var i=l.facets&&l.facets[t]||{};p.disjunctiveFacets[r]={name:t,data:Na({},e,i),exhaustive:a.exhaustiveFacetsCount},vs(p.disjunctiveFacets[r],a.facets_stats,t),f.disjunctiveFacetsRefinements[t]&&zi(f.disjunctiveFacetsRefinements[t],function(e){!p.disjunctiveFacets[r].data[e]&&-1<ta(f.disjunctiveFacetsRefinements[t],e)&&(p.disjunctiveFacets[r].data[e]=0)})}}),n++}),zi(f.getRefinedHierarchicalFacets(),function(e){var o=f.getHierarchicalFacetByName(e),s=f._getHierarchicalFacetSeparator(o),c=f.getHierarchicalRefinement(e);if(!(0===c.length||c[0].split(s).length<2)){var t=r[n];zi(t.facets,function(e,t){var r=sn(f.hierarchicalFacets,{name:o.name}),n=sn(p.hierarchicalFacets[r],{attribute:t});if(-1!==n){var i={};if(0<c.length){var a=c[0].split(s)[0];i[a]=p.hierarchicalFacets[r][n].data[a]}p.hierarchicalFacets[r][n].data=Na(i,e,p.hierarchicalFacets[r][n].data)}}),n++}}),zi(f.facetsExcludes,function(e,t){var r=h[t];p.facets[r]={name:t,data:l.facets[t],exhaustive:l.exhaustiveFacetsCount},zi(e,function(e){p.facets[r]=p.facets[r]||{name:t},p.facets[r].data=p.facets[r].data||{},p.facets[r].data[e]=0})}),this.hierarchicalFacets=Gi(this.hierarchicalFacets,ds(f)),this.facets=Wa(this.facets),this.disjunctiveFacets=Wa(this.disjunctiveFacets),this._state=f}function gs(e,t){if(!t.data||0===t.data.length)return t;var r=e(Gi(t.data,is(gs,e)));return Da({},t,{data:r})}function ys(e,t){return t.sort(e)}function bs(e,t){var r=cn(e,{name:t});return r&&r.stats}function Rs(e,t,r,n,i){var a=cn(i,{name:r});return{type:t,attributeName:r,name:n,count:Br(a,"data["+n+"]")||0,exhaustive:Br(a,"exhaustive")||!1}}ms.prototype.getFacetByName=function(e){var t={name:e};return cn(this.facets,t)||cn(this.disjunctiveFacets,t)||cn(this.hierarchicalFacets,t)},ms.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],ms.prototype.getFacetValues=function(e,t){var r=function(r,n){var e={name:n};if(r._state.isConjunctiveFacet(n)){var t=cn(r.facets,e);return t?Gi(t.data,function(e,t){return{name:t,count:e,isRefined:r._state.isFacetRefined(n,t),isExcluded:r._state.isExcludeRefined(n,t)}}):[]}if(r._state.isDisjunctiveFacet(n)){var i=cn(r.disjunctiveFacets,e);return i?Gi(i.data,function(e,t){return{name:t,count:e,isRefined:r._state.isDisjunctiveFacetRefined(n,t)}}):[]}if(r._state.isHierarchicalFacet(n))return cn(r.hierarchicalFacets,e)}(this,e);if(!r)throw new Error(e+" is not a retrieved facet.");var n=Na({},t,{sortBy:ms.DEFAULT_SORT});if(Array.isArray(n.sortBy)){var i=us(n.sortBy,ms.DEFAULT_SORT);return Array.isArray(r)?ro(r,i[0],i[1]):gs(os(ro,i[0],i[1]),r)}if(de(n.sortBy))return Array.isArray(r)?r.sort(n.sortBy):gs(is(ys,n.sortBy),r);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},ms.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return bs(this.facets,e);if(this._state.isDisjunctiveFacet(e))return bs(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},ms.prototype.getRefinements=function(){var r=this._state,n=this,i=[];return zi(r.facetsRefinements,function(e,t){zi(e,function(e){i.push(Rs(r,"facet",t,e,n.facets))})}),zi(r.facetsExcludes,function(e,t){zi(e,function(e){i.push(Rs(r,"exclude",t,e,n.facets))})}),zi(r.disjunctiveFacetsRefinements,function(e,t){zi(e,function(e){i.push(Rs(r,"disjunctive",t,e,n.disjunctiveFacets))})}),zi(r.hierarchicalFacetsRefinements,function(e,t){zi(e,function(e){i.push(function(e,t,r,n){for(var i=cn(n,{name:t}),a=e.getHierarchicalFacetByName(t),o=r.split(a.separator),s=o[o.length-1],c=0;void 0!==i&&c<o.length;++c)i=cn(i.data,{name:o[c]});var u=Br(i,"count"),f=Br(i,"exhaustive");return{type:"hierarchical",attributeName:t,name:s,count:u||0,exhaustive:f||!1}}(r,t,e,n.hierarchicalFacets))})}),zi(r.numericRefinements,function(e,r){zi(e,function(e,t){zi(e,function(e){i.push({type:"numeric",attributeName:r,name:e,numericValue:e,operator:t})})})}),zi(r.tagRefinements,function(e){i.push({type:"tag",attributeName:"_tags",name:e})}),i};var xs=ms,Fs=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8},_s=S(function(e){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),js=S(function(e,d){var s=/%[sdj%]/g;d.format=function(e){if(!x(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(c(arguments[r]));return t.join(" ")}r=1;for(var n=arguments,i=n.length,a=String(e).replace(s,function(e){if("%%"===e)return"%";if(i<=r)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),o=n[r];r<i;o=n[++r])b(o)||!u(o)?a+=" "+o:a+=" "+c(o);return a},d.deprecate=function(e,t){if(F(E.process))return function(){return d.deprecate(e,t).apply(this,arguments)};var r=!1;return function(){return r||(console.error(t),r=!0),e.apply(this,arguments)}};var n,i={};function c(e,t){var r={seen:[],stylize:o};return 3<=arguments.length&&(r.depth=arguments[2]),4<=arguments.length&&(r.colors=arguments[3]),y(t)?r.showHidden=t:t&&d._extend(r,t),F(r.showHidden)&&(r.showHidden=!1),F(r.depth)&&(r.depth=2),F(r.colors)&&(r.colors=!1),F(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=a),p(r,e,r.depth)}function a(e,t){var r=c.styles[t];return r?"["+c.colors[r][0]+"m"+e+"["+c.colors[r][1]+"m":e}function o(e,t){return e}function p(t,r,n){if(t.customInspect&&r&&P(r.inspect)&&r.inspect!==d.inspect&&(!r.constructor||r.constructor.prototype!==r)){var e=r.inspect(n,t);return x(e)||(e=p(t,e,n)),e}var i=function(e,t){if(F(t))return e.stylize("undefined","undefined");if(x(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(R(t))return e.stylize(""+t,"number");if(y(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(t,r);if(i)return i;var a,o=Object.keys(r),s=(a={},o.forEach(function(e,t){a[e]=!0}),a);if(t.showHidden&&(o=Object.getOwnPropertyNames(r)),w(r)&&(0<=o.indexOf("message")||0<=o.indexOf("description")))return v(r);if(0===o.length){if(P(r)){var c=r.name?": "+r.name:"";return t.stylize("[Function"+c+"]","special")}if(_(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(j(r))return t.stylize(Date.prototype.toString.call(r),"date");if(w(r))return v(r)}var u,f="",l=!1,h=["{","}"];(g(r)&&(l=!0,h=["[","]"]),P(r))&&(f=" [Function"+(r.name?": "+r.name:"")+"]");return _(r)&&(f=" "+RegExp.prototype.toString.call(r)),j(r)&&(f=" "+Date.prototype.toUTCString.call(r)),w(r)&&(f=" "+v(r)),0!==o.length||l&&0!=r.length?n<0?_(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),u=l?function(t,r,n,i,e){for(var a=[],o=0,s=r.length;o<s;++o)S(r,String(o))?a.push(m(t,r,n,i,String(o),!0)):a.push("");return e.forEach(function(e){e.match(/^\d+$/)||a.push(m(t,r,n,i,e,!0))}),a}(t,r,n,s,o):o.map(function(e){return m(t,r,n,s,e,l)}),t.seen.pop(),function(e,t,r){if(60<e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0))return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(u,f,h)):h[0]+f+h[1]}function v(e){return"["+Error.prototype.toString.call(e)+"]"}function m(e,t,r,n,i,a){var o,s,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),S(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(c.value)<0?-1<(s=b(r)?p(e,c.value,null):p(e,c.value,r-1)).indexOf("\n")&&(s=a?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),F(o)){if(a&&i.match(/^\d+$/))return s;o=(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),e.stylize(o,"string"))}return o+": "+s}function g(e){return Array.isArray(e)}function y(e){return"boolean"==typeof e}function b(e){return null===e}function R(e){return"number"==typeof e}function x(e){return"string"==typeof e}function F(e){return void 0===e}function _(e){return u(e)&&"[object RegExp]"===t(e)}function u(e){return"object"==typeof e&&null!==e}function j(e){return u(e)&&"[object Date]"===t(e)}function w(e){return u(e)&&("[object Error]"===t(e)||e instanceof Error)}function P(e){return"function"==typeof e}function t(e){return Object.prototype.toString.call(e)}function r(e){return e<10?"0"+e.toString(10):e.toString(10)}d.debuglog=function(t){if(F(n)&&(n=""),t=t.toUpperCase(),!i[t])if(new RegExp("\\b"+t+"\\b","i").test(n)){var r=O.pid;i[t]=function(){var e=d.format.apply(d,arguments);console.error("%s %d: %s",t,r,e)}}else i[t]=function(){};return i[t]},(d.inspect=c).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]},c.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},d.isArray=g,d.isBoolean=y,d.isNull=b,d.isNullOrUndefined=function(e){return null==e},d.isNumber=R,d.isString=x,d.isSymbol=function(e){return"symbol"==typeof e},d.isUndefined=F,d.isRegExp=_,d.isObject=u,d.isDate=j,d.isError=w,d.isFunction=P,d.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},d.isBuffer=Fs;var f=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}d.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[r(e.getHours()),r(e.getMinutes()),r(e.getSeconds())].join(":"),[e.getDate(),f[e.getMonth()],t].join(" ")),d.format.apply(d,arguments))},d.inherits=_s,d._extend=function(e,t){if(!t||!u(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}});js.format,js.deprecate,js.debuglog,js.inspect,js.isArray,js.isBoolean,js.isNull,js.isNullOrUndefined,js.isNumber,js.isString,js.isSymbol,js.isUndefined,js.isRegExp,js.isObject,js.isDate,js.isError,js.isFunction,js.isPrimitive,js.isBuffer,js.log,js.inherits,js._extend;function ws(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var Ps=ws;function Ss(e){return"function"==typeof e}function Os(e){return"object"==typeof e&&null!==e}function Es(e){return void 0===e}function Ts(e,t){this.main=e,this.fn=t,this.lastResults=null}(ws.EventEmitter=ws).prototype._events=void 0,ws.prototype._maxListeners=void 0,ws.defaultMaxListeners=10,ws.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},ws.prototype.emit=function(e){var t,r,n,i,a,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||Os(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var s=new Error('Uncaught, unspecified "error" event. ('+t+")");throw s.context=t,s}if(Es(r=this._events[e]))return!1;if(Ss(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:i=Array.prototype.slice.call(arguments,1),r.apply(this,i)}else if(Os(r))for(i=Array.prototype.slice.call(arguments,1),n=(o=r.slice()).length,a=0;a<n;a++)o[a].apply(this,i);return!0},ws.prototype.on=ws.prototype.addListener=function(e,t){var r;if(!Ss(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,Ss(t.listener)?t.listener:t),this._events[e]?Os(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,Os(this._events[e])&&!this._events[e].warned&&(r=Es(this._maxListeners)?ws.defaultMaxListeners:this._maxListeners)&&0<r&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},ws.prototype.once=function(e,t){if(!Ss(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},ws.prototype.removeListener=function(e,t){var r,n,i,a;if(!Ss(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(i=(r=this._events[e]).length,n=-1,r===t||Ss(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Os(r)){for(a=i;0<a--;)if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},ws.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(Ss(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},ws.prototype.listeners=function(e){return this._events&&this._events[e]?Ss(this._events[e])?[this._events[e]]:this._events[e].slice():[]},ws.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(Ss(t))return 1;if(t)return t.length}return 0},ws.listenerCount=function(e,t){return e.listenerCount(t)},js.inherits(Ts,Ps.EventEmitter),Ts.prototype.detach=function(){this.removeAllListeners(),this.main.detachDerivedHelper(this)},Ts.prototype.getModifiedState=function(e){return this.fn(e)};var As=Ts,Ns={_getQueries:function(i,a){var o=[];return o.push({indexName:i,params:Ns._getHitsSearchParams(a)}),zi(a.getRefinedDisjunctiveFacets(),function(e){o.push({indexName:i,params:Ns._getDisjunctiveFacetSearchParams(a,e)})}),zi(a.getRefinedHierarchicalFacets(),function(e){var t=a.getHierarchicalFacetByName(e),r=a.getHierarchicalRefinement(e),n=a._getHierarchicalFacetSeparator(t);0<r.length&&1<r[0].split(n).length&&o.push({indexName:i,params:Ns._getDisjunctiveFacetSearchParams(a,e,!0)})}),o},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(Ns._getHitsHierarchicalFacetsAttributes(e)),r=Ns._getFacetFilters(e),n=Ns._getNumericFilters(e),i={facets:t,tagFilters:Ns._getTagFilters(e)};return 0<r.length&&(i.facetFilters=r),0<n.length&&(i.numericFilters=n),Da(e.getQueryParams(),i)},_getDisjunctiveFacetSearchParams:function(e,t,r){var n=Ns._getFacetFilters(e,t,r),i=Ns._getNumericFilters(e,t),a={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:Ns._getTagFilters(e),analytics:!1,clickAnalytics:!1},o=e.getHierarchicalFacetByName(t);return a.facets=o?Ns._getDisjunctiveHierarchicalFacetAttribute(e,o,r):t,0<i.length&&(a.numericFilters=i),0<n.length&&(a.facetFilters=n),Da(e.getQueryParams(),a)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var i=[];return zi(e.numericRefinements,function(e,n){zi(e,function(e,r){t!==n&&zi(e,function(e){if(Array.isArray(e)){var t=Gi(e,function(e){return n+r+e});i.push(t)}else i.push(n+r+e)})})}),i},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(c,u,f){var l=[];return zi(c.facetsRefinements,function(e,t){zi(e,function(e){l.push(t+":"+e)})}),zi(c.facetsExcludes,function(e,t){zi(e,function(e){l.push(t+":-"+e)})}),zi(c.disjunctiveFacetsRefinements,function(e,t){if(t!==u&&e&&0!==e.length){var r=[];zi(e,function(e){r.push(t+":"+e)}),l.push(r)}}),zi(c.hierarchicalFacetsRefinements,function(e,t){var r=e[0];if(void 0!==r){var n,i,a=c.getHierarchicalFacetByName(t),o=c._getHierarchicalFacetSeparator(a),s=c._getHierarchicalRootPath(a);if(u===t){if(-1===r.indexOf(o)||!s&&!0===f||s&&s.split(o).length===r.split(o).length)return;r=s?(i=s.split(o).length-1,s):(i=r.split(o).length-2,r.slice(0,r.lastIndexOf(o))),n=a.attributes[i]}else i=r.split(o).length-1,n=a.attributes[i];n&&l.push([n+":"+r])}}),l},_getHitsHierarchicalFacetsAttributes:function(o){return Xi(o.hierarchicalFacets,function(e,t){var r=o.getHierarchicalRefinement(t.name)[0];if(!r)return e.push(t.attributes[0]),e;var n=o._getHierarchicalFacetSeparator(t),i=r.split(n).length,a=t.attributes.slice(0,i+1);return e.concat(a)},[])},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,r){var n=e._getHierarchicalFacetSeparator(t);if(!0===r){var i=e._getHierarchicalRootPath(t),a=0;return i&&(a=i.split(n).length),[t.attributes[a]]}var o=(e.getHierarchicalRefinement(t.name)[0]||"").split(n).length-1;return t.attributes.slice(0,o+1)},getSearchForFacetQuery:function(e,t,r,n){var i=n.isDisjunctiveFacet(e)?n.clearRefinements(e):n,a={facetQuery:t,facetName:e};return"number"==typeof r&&(a.maxFacetHits=r),Da(Ns._getHitsSearchParams(i),a)}},Cs=Ns;var Is=function(e,n,i,a){return Ui(e,function(e,t,r){n(a,i(e),t,r)}),a};var Hs=function(r,n){return function(e,t){return Is(e,r,n(t),{})}},Qs=Object.prototype.toString,Ms=Hs(function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=Qs.call(t)),e[t]=r},_i(qr)),Ds={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"},Bs=Ms(Ds),Ls={ENCODED_PARAMETERS:Vt(Bs),decode:function(e){return Bs[e]},encode:function(e){return Ds[e]}},ks=S(function(e,a){var o=Object.prototype.hasOwnProperty,s=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}();a.arrayToObject=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},a.merge=function(r,n,i){if(!n)return r;if("object"!=typeof n){if(Array.isArray(r))r.push(n);else{if("object"!=typeof r)return[r,n];(i.plainObjects||i.allowPrototypes||!o.call(Object.prototype,n))&&(r[n]=!0)}return r}if("object"!=typeof r)return[r].concat(n);var e=r;return Array.isArray(r)&&!Array.isArray(n)&&(e=a.arrayToObject(r,i)),Array.isArray(r)&&Array.isArray(n)?(n.forEach(function(e,t){o.call(r,t)?r[t]&&"object"==typeof r[t]?r[t]=a.merge(r[t],e,i):r.push(e):r[t]=e}),r):Object.keys(n).reduce(function(e,t){var r=n[t];return o.call(e,t)?e[t]=a.merge(e[t],r,i):e[t]=r,e},e)},a.assign=function(e,r){return Object.keys(r).reduce(function(e,t){return e[t]=r[t],e},e)},a.decode=function(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch(e){return t}},a.encode=function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),r="",n=0;n<t.length;++n){var i=t.charCodeAt(n);45===i||46===i||95===i||126===i||48<=i&&i<=57||65<=i&&i<=90||97<=i&&i<=122?r+=t.charAt(n):i<128?r+=s[i]:i<2048?r+=s[192|i>>6]+s[128|63&i]:i<55296||57344<=i?r+=s[224|i>>12]+s[128|i>>6&63]+s[128|63&i]:(n+=1,i=65536+((1023&i)<<10|1023&t.charCodeAt(n)),r+=s[240|i>>18]+s[128|i>>12&63]+s[128|i>>6&63]+s[128|63&i])}return r},a.compact=function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],n=0;n<t.length;++n)for(var i=t[n],a=i.obj[i.prop],o=Object.keys(a),s=0;s<o.length;++s){var c=o[s],u=a[c];"object"==typeof u&&null!==u&&-1===r.indexOf(u)&&(t.push({obj:a,prop:c}),r.push(u))}return function(e){for(var t;e.length;){var r=e.pop();if(t=r.obj[r.prop],Array.isArray(t)){for(var n=[],i=0;i<t.length;++i)void 0!==t[i]&&n.push(t[i]);r.obj[r.prop]=n}}return t}(t)},a.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},a.isBuffer=function(e){return null!=e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}}),Us=(ks.arrayToObject,ks.merge,ks.assign,ks.decode,ks.encode,ks.compact,ks.isRegExp,ks.isBuffer,String.prototype.replace),Vs=/%20/g,qs={default:"RFC3986",formatters:{RFC1738:function(e){return Us.call(e,Vs,"+")},RFC3986:function(e){return e}},RFC1738:"RFC1738",RFC3986:"RFC3986"},Ws={brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},zs=Date.prototype.toISOString,$s={delimiter:"&",encode:!0,encoder:ks.encode,encodeValuesOnly:!1,serializeDate:function(e){return zs.call(e)},skipNulls:!1,strictNullHandling:!1},Js=function e(t,r,n,i,a,o,s,c,u,f,l,h){var d=t;if("function"==typeof s)d=s(r,d);else if(d instanceof Date)d=f(d);else if(null===d){if(i)return o&&!h?o(r,$s.encoder):r;d=""}if("string"==typeof d||"number"==typeof d||"boolean"==typeof d||ks.isBuffer(d))return o?[l(h?r:o(r,$s.encoder))+"="+l(o(d,$s.encoder))]:[l(r)+"="+l(String(d))];var p,v=[];if(void 0===d)return v;if(Array.isArray(s))p=s;else{var m=Object.keys(d);p=c?m.sort(c):m}for(var g=0;g<p.length;++g){var y=p[g];a&&null===d[y]||(v=Array.isArray(d)?v.concat(e(d[y],n(r,y),n,i,a,o,s,c,u,f,l,h)):v.concat(e(d[y],r+(u?"."+y:"["+y+"]"),n,i,a,o,s,c,u,f,l,h)))}return v},Ys=Object.prototype.hasOwnProperty,Gs={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:ks.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},Ks=function(e,t,r){if(e){var n=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,a=/(\[[^[\]]*])/.exec(n),o=a?n.slice(0,a.index):n,s=[];if(o){if(!r.plainObjects&&Ys.call(Object.prototype,o)&&!r.allowPrototypes)return;s.push(o)}for(var c=0;null!==(a=i.exec(n))&&c<r.depth;){if(c+=1,!r.plainObjects&&Ys.call(Object.prototype,a[1].slice(1,-1))&&!r.allowPrototypes)return;s.push(a[1])}return a&&s.push("["+n.slice(a.index)+"]"),function(e,t,r){for(var n=t,i=e.length-1;0<=i;--i){var a,o=e[i];if("[]"===o)a=(a=[]).concat(n);else{a=r.plainObjects?Object.create(null):{};var s="["===o.charAt(0)&&"]"===o.charAt(o.length-1)?o.slice(1,-1):o,c=parseInt(s,10);!isNaN(c)&&o!==s&&String(c)===s&&0<=c&&r.parseArrays&&c<=r.arrayLimit?(a=[])[c]=n:a[s]=n}n=a}return n}(s,t,r)}},Zs=function(e,t){var r=t?ks.assign({},t):{};if(null!==r.decoder&&void 0!==r.decoder&&"function"!=typeof r.decoder)throw new TypeError("Decoder has to be a function.");if(r.ignoreQueryPrefix=!0===r.ignoreQueryPrefix,r.delimiter="string"==typeof r.delimiter||ks.isRegExp(r.delimiter)?r.delimiter:Gs.delimiter,r.depth="number"==typeof r.depth?r.depth:Gs.depth,r.arrayLimit="number"==typeof r.arrayLimit?r.arrayLimit:Gs.arrayLimit,r.parseArrays=!1!==r.parseArrays,r.decoder="function"==typeof r.decoder?r.decoder:Gs.decoder,r.allowDots="boolean"==typeof r.allowDots?r.allowDots:Gs.allowDots,r.plainObjects="boolean"==typeof r.plainObjects?r.plainObjects:Gs.plainObjects,r.allowPrototypes="boolean"==typeof r.allowPrototypes?r.allowPrototypes:Gs.allowPrototypes,r.parameterLimit="number"==typeof r.parameterLimit?r.parameterLimit:Gs.parameterLimit,r.strictNullHandling="boolean"==typeof r.strictNullHandling?r.strictNullHandling:Gs.strictNullHandling,""===e||null==e)return r.plainObjects?Object.create(null):{};for(var n="string"==typeof e?function(e,t){for(var r={},n=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=n.split(t.delimiter,i),o=0;o<a.length;++o){var s,c,u=a[o],f=u.indexOf("]="),l=-1===f?u.indexOf("="):f+1;c=-1===l?(s=t.decoder(u,Gs.decoder),t.strictNullHandling?null:""):(s=t.decoder(u.slice(0,l),Gs.decoder),t.decoder(u.slice(l+1),Gs.decoder)),Ys.call(r,s)?r[s]=[].concat(r[s]).concat(c):r[s]=c}return r}(e,r):e,i=r.plainObjects?Object.create(null):{},a=Object.keys(n),o=0;o<a.length;++o){var s=a[o],c=Ks(s,n[s],r);i=ks.merge(i,c,r)}return ks.compact(i)},Xs=function(e,t){var r=e,n=t?ks.assign({},t):{};if(null!==n.encoder&&void 0!==n.encoder&&"function"!=typeof n.encoder)throw new TypeError("Encoder has to be a function.");var i=void 0===n.delimiter?$s.delimiter:n.delimiter,a="boolean"==typeof n.strictNullHandling?n.strictNullHandling:$s.strictNullHandling,o="boolean"==typeof n.skipNulls?n.skipNulls:$s.skipNulls,s="boolean"==typeof n.encode?n.encode:$s.encode,c="function"==typeof n.encoder?n.encoder:$s.encoder,u="function"==typeof n.sort?n.sort:null,f=void 0!==n.allowDots&&n.allowDots,l="function"==typeof n.serializeDate?n.serializeDate:$s.serializeDate,h="boolean"==typeof n.encodeValuesOnly?n.encodeValuesOnly:$s.encodeValuesOnly;if(void 0===n.format)n.format=qs.default;else if(!Object.prototype.hasOwnProperty.call(qs.formatters,n.format))throw new TypeError("Unknown format option provided.");var d,p,v=qs.formatters[n.format];"function"==typeof n.filter?r=(p=n.filter)("",r):Array.isArray(n.filter)&&(d=p=n.filter);var m,g=[];if("object"!=typeof r||null===r)return"";m=n.arrayFormat in Ws?n.arrayFormat:"indices"in n?n.indices?"indices":"repeat":"indices";var y=Ws[m];d||(d=Object.keys(r)),u&&d.sort(u);for(var b=0;b<d.length;++b){var R=d[b];o&&null===r[R]||(g=g.concat(Js(r[R],R,y,a,o,s?c:null,p,u,f,l,v,h)))}var x=g.join(i),F=!0===n.addQueryPrefix?"?":"";return 0<x.length?F+x:""},ec=Mi(function(e,t,r){var n=1;if(r.length){var i=ko(r,Mo(ec));n|=32}return rs(e,n,t,r,i)});ec.placeholder={};var tc=ec;var rc=function(r,e){return ls(r,e,function(e,t){return Ur(r,t)})},nc=Oi(function(e,t){return null==e?{}:rc(e,t)});var ic=function(e,n){var i={};return n=Jr(n,3),Ui(e,function(e,t,r){dn(i,n(e,t,r),e)}),i};var ac=function(e,n){var i={};return n=Jr(n,3),Ui(e,function(e,t,r){dn(i,t,n(e,t,r))}),i},oc=ks.encode;function sc(e){return pi(e)?ac(e,sc):Array.isArray(e)?Gi(e,sc):oa(e)?oc(e):e}var cc=["dFR","fR","nR","hFR","tR"],uc=Ls.ENCODED_PARAMETERS;function fc(e,t,r,n){if(null!==e&&(r=r.replace(e,""),n=n.replace(e,"")),r=t[r]||r,n=t[n]||n,-1!==uc.indexOf(r)||-1!==uc.indexOf(n)){if("q"===r)return-1;if("q"===n)return 1;var i=-1!==cc.indexOf(r),a=-1!==cc.indexOf(n);if(i&&!a)return 1;if(a&&!i)return-1}return r.localeCompare(n)}var lc={getStateFromQueryString:function(e,t){var n=t&&t.prefix||"",r=t&&t.mapping||{},i=Ms(r),a=Zs(e),o=new RegExp("^"+n),s=ic(a,function(e,t){var r=n&&o.test(t)?t.replace(o,""):t;return Ls.decode(i[r]||r)||r}),c=qa._parseNumbers(s);return nc(c,qa.PARAMETERS)},getUnrecognizedParametersInQueryString:function(e,t){var r=t&&t.prefix,n=t&&t.mapping||{},i=Ms(n),a={},o=Zs(e);if(r){var s=new RegExp("^"+r);zi(o,function(e,t){s.test(t)||(a[t]=e)})}else zi(o,function(e,t){Ls.decode(i[t]||t)||(a[t]=e)});return a},getQueryStringFromState:function(e,t){var r=t&&t.moreAttributes,n=t&&t.prefix||"",i=t&&t.mapping||{},a=t&&t.safe||!1,o=Ms(i),s=a?e:sc(e),c=ic(s,function(e,t){var r=Ls.encode(t);return n+(i[r]||r)}),u=""===n?null:new RegExp("^"+n),f=tc(fc,null,u,o);if(fn(r))return Xs(c,{encode:a,sort:f});var l=Xs(c,{encode:a,sort:f}),h=Xs(r,{encode:a});return l?l+"&"+h:h}},hc="2.26.0";function dc(e,t,r){e.addAlgoliaAgent&&!mc(e)&&e.addAlgoliaAgent("JS Helper "+hc),this.setClient(e);var n=r||{};n.index=t,this.state=qa.make(n),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1,this.derivedHelpers=[],this._currentNbQueries=0}function pc(e){if(e<0)throw new Error("Page requested below 0.");return this._change(this.state.setPage(e)),this}function vc(){return this.state.page}function mc(e){var t=e._ua;return!!t&&-1!==t.indexOf("JS Helper")}js.inherits(dc,Ps.EventEmitter),dc.prototype.search=function(){return this._search(),this},dc.prototype.getQuery=function(){var e=this.state;return Cs._getHitsSearchParams(e)},dc.prototype.searchOnce=function(e,t){var r=e?this.state.setQueryParameters(e):this.state,n=Cs._getQueries(r.index,r),i=this;if(this._currentNbQueries++,this.emit("searchOnce",r),!t)return this.client.search(n).then(function(e){return i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),{content:new xs(r,e.results),state:r,_originalResponse:e}},function(e){throw i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),e});this.client.search(n).then(function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(null,new xs(r,e.results),r)}).catch(function(e){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(e,null,r)})},dc.prototype.searchForFacetValues=function(t,e,r,n){var i=this.state.setQueryParameters(n||{}),a=i.isDisjunctiveFacet(t),o=Cs.getSearchForFacetQuery(t,e,r,i);this._currentNbQueries++;var s=this;return this.emit("searchForFacetValues",i,t,e),("function"==typeof this.client.searchForFacetValues?this.client.searchForFacetValues([{indexName:i.index,params:o}]):this.client.initIndex(i.index).searchForFacetValues(o)).then(function(e){return s._currentNbQueries--,0===s._currentNbQueries&&s.emit("searchQueueEmpty"),(e=Array.isArray(e)?e[0]:e).facetHits=zi(e.facetHits,function(e){e.isRefined=a?i.isDisjunctiveFacetRefined(t,e.value):i.isFacetRefined(t,e.value)}),e},function(e){throw s._currentNbQueries--,0===s._currentNbQueries&&s.emit("searchQueueEmpty"),e})},dc.prototype.setQuery=function(e){return this._change(this.state.setPage(0).setQuery(e)),this},dc.prototype.clearRefinements=function(e){return this._change(this.state.setPage(0).clearRefinements(e)),this},dc.prototype.clearTags=function(){return this._change(this.state.setPage(0).clearTags()),this},dc.prototype.addDisjunctiveFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(e,t)),this},dc.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},dc.prototype.addHierarchicalFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addHierarchicalFacetRefinement(e,t)),this},dc.prototype.addNumericRefinement=function(e,t,r){return this._change(this.state.setPage(0).addNumericRefinement(e,t,r)),this},dc.prototype.addFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addFacetRefinement(e,t)),this},dc.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},dc.prototype.addFacetExclusion=function(e,t){return this._change(this.state.setPage(0).addExcludeRefinement(e,t)),this},dc.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},dc.prototype.addTag=function(e){return this._change(this.state.setPage(0).addTagRefinement(e)),this},dc.prototype.removeNumericRefinement=function(e,t,r){return this._change(this.state.setPage(0).removeNumericRefinement(e,t,r)),this},dc.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(e,t)),this},dc.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},dc.prototype.removeHierarchicalFacetRefinement=function(e){return this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(e)),this},dc.prototype.removeFacetRefinement=function(e,t){return this._change(this.state.setPage(0).removeFacetRefinement(e,t)),this},dc.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},dc.prototype.removeFacetExclusion=function(e,t){return this._change(this.state.setPage(0).removeExcludeRefinement(e,t)),this},dc.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},dc.prototype.removeTag=function(e){return this._change(this.state.setPage(0).removeTagRefinement(e)),this},dc.prototype.toggleFacetExclusion=function(e,t){return this._change(this.state.setPage(0).toggleExcludeFacetRefinement(e,t)),this},dc.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},dc.prototype.toggleRefinement=function(e,t){return this.toggleFacetRefinement(e,t)},dc.prototype.toggleFacetRefinement=function(e,t){return this._change(this.state.setPage(0).toggleFacetRefinement(e,t)),this},dc.prototype.toggleRefine=function(){return this.toggleFacetRefinement.apply(this,arguments)},dc.prototype.toggleTag=function(e){return this._change(this.state.setPage(0).toggleTagRefinement(e)),this},dc.prototype.nextPage=function(){return this.setPage(this.state.page+1)},dc.prototype.previousPage=function(){return this.setPage(this.state.page-1)},dc.prototype.setCurrentPage=pc,dc.prototype.setPage=pc,dc.prototype.setIndex=function(e){return this._change(this.state.setPage(0).setIndex(e)),this},dc.prototype.setQueryParameter=function(e,t){return this._change(this.state.setPage(0).setQueryParameter(e,t)),this},dc.prototype.setState=function(e){return this._change(qa.make(e)),this},dc.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},dc.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],r=this.getState(t);return lc.getQueryStringFromState(r,e)},dc.getConfigurationFromQueryString=lc.getStateFromQueryString,dc.getForeignConfigurationInQueryString=lc.getUnrecognizedParametersInQueryString,dc.prototype.setStateFromQueryString=function(e,t){var r=t&&t.triggerChange||!1,n=lc.getStateFromQueryString(e,t),i=this.state.setQueryParameters(n);r?this.setState(i):this.overrideStateWithoutTriggeringChangeEvent(i)},dc.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new qa(e),this},dc.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},dc.prototype.hasRefinements=function(e){return!fn(this.state.getNumericRefinements(e))||(this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):!!this.state.isHierarchicalFacet(e)&&this.state.isHierarchicalFacetRefined(e))},dc.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},dc.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},dc.prototype.hasTag=function(e){return this.state.isTagRefined(e)},dc.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},dc.prototype.getIndex=function(){return this.state.index},dc.prototype.getCurrentPage=vc,dc.prototype.getPage=vc,dc.prototype.getTags=function(){return this.state.tagRefinements},dc.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},dc.prototype.getRefinements=function(e){var r=[];if(this.state.isConjunctiveFacet(e)){var t=this.state.getConjunctiveRefinements(e);zi(t,function(e){r.push({value:e,type:"conjunctive"})});var n=this.state.getExcludeRefinements(e);zi(n,function(e){r.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var i=this.state.getDisjunctiveRefinements(e);zi(i,function(e){r.push({value:e,type:"disjunctive"})})}var a=this.state.getNumericRefinements(e);return zi(a,function(e,t){r.push({value:e,operator:t,type:"numeric"})}),r},dc.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},dc.prototype.getHierarchicalFacetBreadcrumb=function(e){return this.state.getHierarchicalFacetBreadcrumb(e)},dc.prototype._search=function(){var n=this.state,e=Cs._getQueries(n.index,n),i=[{state:n,queriesCount:e.length,helper:this}];this.emit("search",n,this.lastResults);var t=Gi(this.derivedHelpers,function(e){var t=e.getModifiedState(n),r=Cs._getQueries(t.index,t);return i.push({state:t,queriesCount:r.length,helper:e}),e.emit("search",t,e.lastResults),r}),r=e.concat(bi(t)),a=this._queryId++;this._currentNbQueries++;try{this.client.search(r).then(this._dispatchAlgoliaResponse.bind(this,i,a)).catch(this._dispatchAlgoliaError.bind(this,a))}catch(e){this.emit("error",e)}},dc.prototype._dispatchAlgoliaResponse=function(e,t,r){if(!(t<this._lastQueryIdReceived)){this._currentNbQueries-=t-this._lastQueryIdReceived,this._lastQueryIdReceived=t,0===this._currentNbQueries&&this.emit("searchQueueEmpty");var o=r.results;zi(e,function(e){var t=e.state,r=e.queriesCount,n=e.helper,i=o.splice(0,r),a=n.lastResults=new xs(t,i);n.emit("result",a,t)})}},dc.prototype._dispatchAlgoliaError=function(e,t){e<this._lastQueryIdReceived||(this._currentNbQueries-=e-this._lastQueryIdReceived,this._lastQueryIdReceived=e,this.emit("error",t),0===this._currentNbQueries&&this.emit("searchQueueEmpty"))},dc.prototype.containsRefinement=function(e,t,r,n){return e||0!==t.length||0!==r.length||0!==n.length},dc.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&0<this.state.disjunctiveRefinements[e].length},dc.prototype._change=function(e){e!==this.state&&(this.state=e,this.emit("change",this.state,this.lastResults))},dc.prototype.clearCache=function(){return this.client.clearCache&&this.client.clearCache(),this},dc.prototype.setClient=function(e){return this.client===e||(e.addAlgoliaAgent&&!mc(e)&&e.addAlgoliaAgent("JS Helper "+hc),this.client=e),this},dc.prototype.getClient=function(){return this.client},dc.prototype.derive=function(e){var t=new As(this,e);return this.derivedHelpers.push(t),t},dc.prototype.detachDerivedHelper=function(e){var t=this.derivedHelpers.indexOf(e);if(-1===t)throw new Error("Derived helper already detached");this.derivedHelpers.splice(t,1)},dc.prototype.hasPendingRequests=function(){return 0<this._currentNbQueries};var gc=dc;function yc(e,t,r){return new gc(e,t,r)}yc.version=hc,yc.AlgoliaSearchHelper=gc,yc.SearchParameters=qa,yc.SearchResults=xs,yc.url=lc;var bc=yc,Rc=bc.SearchParameters,xc=function(e,t){if(e===t)return!0;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var i=Object.prototype.hasOwnProperty,a=0;a<r.length;a++)if(!i.call(t,r[a])||e[r[a]]!==t[r[a]])return!1;return!0},Fc=Promise.resolve(),_c=function(e){Fc.then(e)};function jc(e){var t=e,r=[];return{getState:function(){return t},setState:function(e){t=e,r.forEach(function(e){return e()})},subscribe:function(e){return r.push(e),function(){r.splice(r.indexOf(e),1)}}}}var wc={highlightPreTag:"<ais-highlight-0000000000>",highlightPostTag:"</ais-highlight-0000000000>"};function Pc(e){var t=e.preTag,r=e.postTag,n=e.highlightedValue,i=(void 0===n?"":n).split(t),a=i.shift(),o=""===a?[]:[{value:a,isHighlighted:!1}];if(r===t){var s=!0;i.forEach(function(e){o.push({value:e,isHighlighted:s}),s=!s})}else i.forEach(function(e){var t=e.split(r);o.push({value:t[0],isHighlighted:!0}),""!==t[1]&&o.push({value:t[1],isHighlighted:!1})});return o}var Sc=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};function Oc(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ec(e){var i=e.indexName,t=e.initialState,r=void 0===t?{}:t,n=e.searchClient,a=e.resultsState,o=e.stalledSearchDelay,s=new Rc(Sc({index:i},wc)),c=null,u=bc(n,i,s);u.on("result",y),u.on("error",b),u.on("search",function(){c||(c=setTimeout(function(){var e=Ei(Sc({},p.getState(),{isSearchStalled:!0}),"resultsFacetValues");p.setState(e)},o))});var f={},l={},h=u.state,d=function(e){var t=[],r=!1;function n(){r||(r=!0,_c(function(){r=!1,e()}))}return{registerWidget:function(e){return t.push(e),n(),function(){t.splice(t.indexOf(e),1),n()}},update:n,getWidgets:function(){return t}}}(function(){var e=m(p.getState().widgets);p.setState(Sc({},p.getState(),{metadata:e,searching:!0})),g()}),p=jc({widgets:r,metadata:[],results:a||null,error:null,searching:!1,isSearchStalled:!0,searchingForFacetValues:!1}),v=!1;function m(t){return d.getWidgets().filter(function(e){return Boolean(e.getMetadata)}).map(function(e){return e.getMetadata(t)})}function g(){if(!v){var e=function(){l={};var e=d.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return!(e.context.multiIndexContext||e.props.indexName!==i&&e.props.indexName)}).reduce(function(e,t){return t.getSearchParameters(e)},h);l[e.index]=i;var t=d.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return e.context.multiIndexContext&&e.context.multiIndexContext.targetedIndex!==i||e.props.indexName&&e.props.indexName!==i}).reduce(function(e,t){var r=t.context.multiIndexContext?t.context.multiIndexContext.targetedIndex:t.props.indexName,n=cn(e,function(e){return e.targetedIndex===r});return n?n.widgets.push(t):e.push({targetedIndex:r,widgets:[t]}),e},[]),r=d.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return e.context.multiIndexContext&&e.context.multiIndexContext.targetedIndex===i||e.props.indexName&&e.props.indexName===i}).reduce(function(e,t){return t.getSearchParameters(e)},e);return l[r.index]=i,{sharedParameters:e,mainIndexParameters:r,derivatedWidgets:t}}(u.state),n=e.sharedParameters,t=e.mainIndexParameters,r=e.derivatedWidgets;Object.keys(f).forEach(function(e){return f[e].detach()}),f={},u.setState(n),r.forEach(function(t){var r=t.targetedIndex,e=u.derive(function(){var e=t.widgets.reduce(function(e,t){return t.getSearchParameters(e)},n);return l[e.index]=r,e});e.on("result",y),e.on("error",b),f[r]=e}),u.setState(t),u.search()}}function y(e){var t=p.getState(),r=t.results?t.results:{};r=!fn(f)&&r.getFacetByName?{}:r,fn(f)?r=e:r[l[e.index]]=e;var n=p.getState(),i=n.isSearchStalled;u.hasPendingRequests()||(clearTimeout(c),c=null,i=!1);var a=Ei(Sc({},n,{results:r,isSearchStalled:i,searching:!1,error:null}),"resultsFacetValues");p.setState(a)}function b(e){var t=p.getState(),r=t.isSearchStalled;u.hasPendingRequests()||(clearTimeout(c),r=!1);var n=Ei(Sc({},t,{isSearchStalled:r,error:e,searching:!1}),"resultsFacetValues");p.setState(n)}return{store:p,widgetsManager:d,getWidgetsIds:function(){return p.getState().metadata.reduce(function(e,t){return void 0!==t.id?e.concat(t.id):e},[])},onExternalStateUpdate:function(e){var t=m(e);p.setState(Sc({},p.getState(),{widgets:e,metadata:t,searching:!0})),g()},transitionState:function(e){var r=p.getState().widgets;return d.getWidgets().filter(function(e){return Boolean(e.transitionState)}).reduce(function(e,t){return t.transitionState(r,e)},e)},onSearchForFacetValues:function(e){var r=e.facetName,n=e.query,t=e.maxFacetHits;p.setState(Sc({},p.getState(),{searchingForFacetValues:!0})),u.searchForFacetValues(r,n,t).then(function(e){var t;p.setState(Sc({},p.getState(),{resultsFacetValues:Sc({},p.getState().resultsFacetValues,(t={},Oc(t,r,e.facetHits),Oc(t,"query",n),t)),searchingForFacetValues:!1}))},function(e){p.setState(Sc({},p.getState(),{error:e,searchingForFacetValues:!1}))}).catch(function(e){setTimeout(function(){throw e})})},updateClient:function(e){u.setClient(e),g()},updateIndex:function(e){h=h.setIndex(e),g()},clearCache:function(){u.clearCache(),g()},skipSearch:function(){v=!0}}}var Tc="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ac=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},Nc=function(){function n(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(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}}();var Cc=function(e){function n(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n);var t=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":Tc(t))&&"function"!=typeof t?e:t}(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));t.isControlled=Boolean(e.searchState);var r=t.isControlled?e.searchState:{};return t.isUnmounting=!1,t.aisManager=Ec({indexName:e.indexName,searchClient:e.searchClient,initialState:r,resultsState:e.resultsState,stalledSearchDelay:e.stalledSearchDelay}),t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":Tc(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)}(n,v.Component),Nc(n,[{key:"componentWillReceiveProps",value:function(e){!function(e,t){if(!e.searchState&&t.searchState)throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled");if(e.searchState&&!t.searchState)throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled")}(this.props,e),this.props.indexName!==e.indexName&&this.aisManager.updateIndex(e.indexName),this.props.refresh!==e.refresh&&e.refresh&&this.aisManager.clearCache(),this.props.searchClient!==e.searchClient&&this.aisManager.updateClient(e.searchClient),this.isControlled&&this.aisManager.onExternalStateUpdate(e.searchState)}},{key:"componentWillUnmount",value:function(){this.isUnmounting=!0,this.aisManager.skipSearch()}},{key:"getChildContext",value:function(){return this._aisContextCache||(this._aisContextCache={ais:{onInternalStateUpdate:this.onWidgetsInternalStateUpdate.bind(this),createHrefForState:this.createHrefForState.bind(this),onSearchForFacetValues:this.onSearchForFacetValues.bind(this),onSearchStateChange:this.onSearchStateChange.bind(this),onSearchParameters:this.onSearchParameters.bind(this)}}),{ais:Ac({},this._aisContextCache.ais,{store:this.aisManager.store,widgetsManager:this.aisManager.widgetsManager,mainTargetedIndex:this.props.indexName})}}},{key:"createHrefForState",value:function(e){return e=this.aisManager.transitionState(e),this.isControlled&&this.props.createURL?this.props.createURL(e,this.getKnownKeys()):"#"}},{key:"onWidgetsInternalStateUpdate",value:function(e){e=this.aisManager.transitionState(e),this.onSearchStateChange(e),this.isControlled||this.aisManager.onExternalStateUpdate(e)}},{key:"onSearchStateChange",value:function(e){this.props.onSearchStateChange&&!this.isUnmounting&&this.props.onSearchStateChange(e)}},{key:"onSearchParameters",value:function(e,t,r){if(this.props.onSearchParameters){var n=this.props.searchState?this.props.searchState:{};this.props.onSearchParameters(e,t,r,n)}}},{key:"onSearchForFacetValues",value:function(e){this.aisManager.onSearchForFacetValues(e)}},{key:"getKnownKeys",value:function(){return this.aisManager.getWidgetsIds()}},{key:"render",value:function(){var e=v.Children.count(this.props.children),t=this.props.root,r=t.Root,n=t.props;return 0===e?null:m.createElement(r,n,this.props.children)}}]),n}();Cc.defaultProps={stalledSearchDelay:200},Cc.propTypes={indexName:M.string.isRequired,searchClient:M.object.isRequired,createURL:M.func,refresh:M.bool.isRequired,searchState:M.object,onSearchStateChange:M.func,onSearchParameters:M.func,resultsState:M.oneOfType([M.object,M.array]),children:M.node,root:M.shape({Root:M.oneOfType([M.string,M.func,M.object]),props:M.object}).isRequired,stalledSearchDelay:M.number},Cc.childContextTypes={ais:M.object.isRequired};var Ic=function(){function n(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(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}}();var Hc=function(e){function i(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,i);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":Tc(t))&&"function"!=typeof t?e:t}(this,(i.__proto__||Object.getPrototypeOf(i)).call(this,e)),n=t.ais.widgetsManager;return r.unregisterWidget=n.registerWidget(r),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":Tc(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)}(i,v.Component),Ic(i,[{key:"componentWillMount",value:function(){this.context.ais.onSearchParameters(this.getSearchParameters.bind(this),this.getChildContext(),this.props)}},{key:"componentWillReceiveProps",value:function(e){this.props.indexName!==e.indexName&&this.context.ais.widgetsManager.update()}},{key:"componentWillUnmount",value:function(){this.unregisterWidget()}},{key:"getChildContext",value:function(){return{multiIndexContext:{targetedIndex:this.props.indexName}}}},{key:"getSearchParameters",value:function(e,t){return e.setIndex(this.props?this.props.indexName:t.indexName)}},{key:"render",value:function(){var e=v.Children.count(this.props.children),t=this.props.root,r=t.Root,n=t.props;return 0===e?null:m.createElement(r,n,this.props.children)}}]),i}();Hc.propTypes={indexName:M.string.isRequired,children:M.node,root:M.shape({Root:M.oneOfType([M.string,M.func,M.object]),props:M.object}).isRequired},Hc.childContextTypes={multiIndexContext:M.object.isRequired},Hc.contextTypes={ais:M.object.isRequired};var Qc=Object.prototype.hasOwnProperty;var Mc=function(e,t){return null!=e&&Qc.call(e,t)};var Dc=function(e,t){return null!=e&&kr(e,t,Mc)},Bc=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},Lc=function(){function n(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(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}}();function kc(f){if(!f.displayName)throw new Error("`createConnector` requires you to provide a `displayName` property.");var i=Dc(f,"refine"),a=Dc(f,"searchForFacetValues"),c=Dc(f,"getSearchParameters"),u=Dc(f,"getMetadata"),l=Dc(f,"transitionState"),h=Dc(f,"cleanUp"),d=Dc(f,"shouldComponentUpdate"),p=c||u||l;return function(r){var e,t,s,n;return t=e=function(e){function o(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,o);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":Tc(t))&&"function"!=typeof t?e:t}(this,(o.__proto__||Object.getPrototypeOf(o)).call(this,e,t));s.call(r);var n=t.ais,i=n.store,a=n.widgetsManager;return r.state={props:r.getProvidedProps(Bc({},e,{canRender:!1})),canRender:!1},r.unsubscribe=i.subscribe(function(){r.state.canRender&&r.setState({props:r.getProvidedProps(Bc({},r.props,{canRender:r.state.canRender}))})}),p&&(r.unregisterWidget=a.registerWidget(r)),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":Tc(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)}(o,v.Component),Lc(o,[{key:"getMetadata",value:function(e){return u?f.getMetadata.call(this,this.props,e):{}}},{key:"getSearchParameters",value:function(e){return c?f.getSearchParameters.call(this,e,this.props,this.context.ais.store.getState().widgets):null}},{key:"transitionState",value:function(e,t){return l?f.transitionState.call(this,this.props,e,t):t}},{key:"componentDidMount",value:function(){this.setState({canRender:!0})}},{key:"componentWillMount",value:function(){f.getSearchParameters&&this.context.ais.onSearchParameters(f.getSearchParameters.bind(this),this.context,this.props)}},{key:"componentWillReceiveProps",value:function(e){ia(this.props,e)||(this.setState({props:this.getProvidedProps(e)}),p&&(this.context.ais.widgetsManager.update(),f.transitionState&&this.context.ais.onSearchStateChange(f.transitionState.call(this,e,this.context.ais.store.getState().widgets,this.context.ais.store.getState().widgets))))}},{key:"componentWillUnmount",value:function(){if(this.unsubscribe(),p&&(this.unregisterWidget(),h)){var e=f.cleanUp.call(this,this.props,this.context.ais.store.getState().widgets);this.context.ais.store.setState(Bc({},this.context.ais.store.getState(),{widgets:e})),this.context.ais.onSearchStateChange(function r(n){return Object.keys(n).forEach(function(e){var t=n[e];fn(t)&&pi(t)?delete n[e]:pi(t)&&r(t)}),n}(e))}}},{key:"shouldComponentUpdate",value:function(e,t){if(d)return f.shouldComponentUpdate.call(this,this.props,e,this.state,t);var r=xc(this.props,e);return null===this.state.props||null===t.props?this.state.props!==t.props||!r:!r||!xc(this.state.props,t.props)}},{key:"render",value:function(){if(null===this.state.props)return null;var e=i?{refine:this.refine,createURL:this.createURL}:{},t=a?{searchForItems:this.searchForFacetValues}:{};return m.createElement(r,Bc({},this.props,this.state.props,e,t))}}]),o}(),e.displayName=f.displayName+"("+((n=r).displayName||n.name||"UnknownComponent")+")",e.defaultClassNames=r.defaultClassNames,e.propTypes=f.propTypes,e.defaultProps=f.defaultProps,e.contextTypes={ais:M.object.isRequired,multiIndexContext:M.object},s=function(){var u=this;this.getProvidedProps=function(e){var t=u.context.ais.store.getState(),r=t.results,n=t.searching,i=t.error,a=t.widgets,o=t.metadata,s=t.resultsFacetValues,c={results:r,searching:n,error:i,searchingForFacetValues:t.searchingForFacetValues,isSearchStalled:t.isSearchStalled};return f.getProvidedProps.call(u,e,a,c,o,s)},this.refine=function(){for(var e,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];u.context.ais.onInternalStateUpdate((e=f.refine).call.apply(e,[u,u.props,u.context.ais.store.getState().widgets].concat(r)))},this.searchForFacetValues=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];u.context.ais.onSearchForFacetValues(f.searchForFacetValues.apply(f,[u.props,u.context.ais.store.getState().widgets].concat(t)))},this.createURL=function(){for(var e,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];return u.context.ais.createHrefForState((e=f.refine).call.apply(e,[u,u.props,u.context.ais.store.getState().widgets].concat(r)))},this.cleanUp=function(){for(var e,t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=f.cleanUp).call.apply(e,[u].concat(r))}},t}}var Uc=function(e,t,r,n){var i=-1,a=Ci,o=!0,s=e.length,c=[],u=t.length;if(!s)return c;r&&(t=Tr(t,Tt(r))),n?(a=Ii,o=!1):200<=t.length&&(a=et,o=!1,t=new Ze(t));e:for(;++i<s;){var f=e[i],l=null==r?f:r(f);if(f=n||0!==f?f:0,o&&l==l){for(var h=u;h--;)if(t[h]===l)continue e;c.push(f)}else a(t,l,n)||c.push(f)}return c},Vc=Mi(function(e,t){return Di(e)?Uc(e,yi(t,1,Di,!0)):[]}),qc=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};function Wc(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zc(e){return e&&e.multiIndexContext?e.multiIndexContext.targetedIndex:e.ais.mainTargetedIndex}function $c(e,t){return e.results&&!e.results.hits?e.results[zc(t)]?e.results[zc(t)]:null:e.results?e.results:null}function Jc(e){return e&&e.multiIndexContext}function Yc(t,e,r,n,i){return Jc(r)?i?(p=t,v=e,m=n,g=i,b=zc(r),R=m?{page:1}:void 0,x=Dc(p,"indices."+b)?qc({},p.indices,Wc({},b,qc({},p.indices[b],(Wc(y={},g,qc({},p.indices[b][g],v)),Wc(y,"page",1),y)))):qc({},p.indices,Wc({},b,qc(Wc({},g,v),R))),qc({},p,{indices:x})):(u=t,f=e,l=n?{page:1}:void 0,h=zc(r),d=Dc(u,"indices."+h)?qc({},u.indices,Wc({},h,qc({},u.indices[h],f,l))):qc({},u.indices,Wc({},h,qc({},f,l))),qc({},u,{indices:d})):(t.indices&&n&&Object.keys(t.indices).forEach(function(e){t=Yc(t,{page:1},{multiIndexContext:{targetedIndex:e}},!0,i)}),i?(o=e,c=n?{page:1}:void 0,qc({},a=t,Wc({},s=i,qc({},a[s],o)),c)):qc({},t,e,n?{page:1}:void 0));var a,o,s,c,u,f,l,h,d,p,v,m,g,y,b,R,x}function Gc(e){var t=e.match(/^([^.]*)\.(.*)/);return{namespace:t&&t[1],attributeName:t&&t[2]}}function Kc(e,t,r,n,i){var a=5<arguments.length&&void 0!==arguments[5]?arguments[5]:function(e){return e},o=zc(r),s=Gc(n),c=s.namespace,u=s.attributeName;if(Jc(r)&&t.indices&&c&&t.indices[""+o]&&Dc(t.indices[""+o][c],""+u)||Jc(r)&&t.indices&&Dc(t,"indices."+o+"."+n)||!Jc(r)&&c&&Dc(t[c],u)||!Jc(r)&&Dc(t,n)){return a(Jc(r)?c?Br(t.indices[""+o][c],u):Br(t.indices[o],n):c?Br(t[c],u):Br(t,n))}return e.defaultRefinement?e.defaultRefinement:i}function Zc(e,t,r){var n=zc(t),i=Gc(r),a=i.namespace,o=i.attributeName;return Jc(t)&&Boolean(e.indices)?function(e){var t=e.searchState,r=e.indexName,n=e.id,i=e.namespace,a=e.attribute,o=t.indices[r];if(i&&o)return qc({},t,{indices:qc({},t.indices,Wc({},r,qc({},o,Wc({},i,Ei(o[i],a)))))});return Ei(t,"indices."+r+"."+n)}({attribute:o,searchState:e,indexName:n,id:r,namespace:a}):function(e){var t=e.searchState,r=e.id,n=e.namespace,i=e.attribute;if(n)return qc({},t,Wc({},n,Ei(t[n],i)));return Ei(t,r)}({attribute:o,searchState:e,id:r,namespace:a})}var Xc=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};function eu(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var tu=kc({displayName:"AlgoliaConfigure",getProvidedProps:function(){return{}},getSearchParameters:function(e,t){var r=Ei(t,"children");return e.setQueryParameters(r)},transitionState:function(e,t,r){var n=Ei(e,"children"),i=this._props?Vc(Vt(this._props),Vt(e)):[];return this._props=e,Yc(r,eu({},"configure",Xc({},Ei(r.configure,i),n)),this.context)},cleanUp:function(r,e){var n="configure",t=zc(this.context),i=Jc(this.context)&&e.indices?e.indices[t]:e,a=(i&&i[n]?Object.keys(i[n]):[]).reduce(function(e,t){return r[t]||(e[t]=i[n][t]),e},{});return Yc(e,eu({},n,a),this.context)}});tu(function(){return null});function ru(e,t,r){return Kc(e,t,r,"query","",function(e){return e||""})}function nu(r){return r.results?r.results.hits&&Array.isArray(r.results.hits)?r.results.hits:Object.keys(r.results).reduce(function(e,t){return[].concat(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)}(e),[{index:t,hits:r.results[t].hits}])},[]):[]}function iu(e,t,r,n){var i,a,o;return Yc(t,(o=r,(a="query")in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0)}var au=kc({displayName:"AlgoliaAutoComplete",getProvidedProps:function(e,t,r){return{hits:nu(r),currentRefinement:ru(e,t,this.context)}},refine:function(e,t,r){return iu(0,t,r,this.context)},cleanUp:function(e,t){return r=t,n=this.context,Zc(r,n,"query");var r,n},getSearchParameters:function(e,t,r){return e.setQuery(ru(t,r,this.context))}});var ou=function(e){return e.attributes[0]};function su(e,t,r,n){var i,a,o,s=ou(e);return Yc(t,(o=r||"",(a=s)in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,"hierarchicalMenu")}var cu=kc({displayName:"AlgoliaBreadcrumb",propTypes:{attributes:function(e,t,r){if(!Array.isArray(e[t])||e[t].some(function(e){return"string"!=typeof e})||e[t].length<1)return new Error("Invalid prop "+t+" supplied to "+r+". Expected an Array of Strings")},transformItems:M.func},getProvidedProps:function(e,t,r){var n=ou(e),i=$c(r,this.context);if(!(Boolean(i)&&Boolean(i.getFacetByName(n))))return{items:[],canRefine:!1};var a=i.getFacetValues(n),o=a.data?function r(e){return e.reduce(function(e,t){return t.isRefined&&(e.push({label:t.name,value:t.path}),t.data&&(e=e.concat(r(t.data)))),e},[])}(a.data):[],s=e.transformItems?e.transformItems(o):o;return{canRefine:0<s.length,items:s}},refine:function(e,t,r){return su(e,t,r,this.context)}}),uu=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},fu=kc({displayName:"AlgoliaCurrentRefinements",propTypes:{transformItems:M.func},getProvidedProps:function(r,e,t,n){var i=n.reduce(function(e,t){return void 0!==t.items&&(r.clearsQuery||"query"!==t.id)?r.clearsQuery&&"query"===t.id&&""===t.items[0].currentRefinement?e:e.concat(t.items.map(function(e){return uu({},e,{id:t.id,index:t.index})})):e},[]),a=r.transformItems?r.transformItems(i):i;return{items:a,canRefine:0<a.length}},refine:function(e,t,r){return(r instanceof Array?r.map(function(e){return e.value}):[r]).reduce(function(e,t){return t(e)},t)}});var lu=function(e){return[e.northEast.lat,e.northEast.lng,e.southWest.lat,e.southWest.lng].join()},hu=/^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/,du=function(e){var t=e.match(hu);return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}},pu=function(e,t,r){var n=Kc(e,t,r,"boundingBox",{});if(!fn(n))return{northEast:{lat:parseFloat(n.northEast.lat),lng:parseFloat(n.northEast.lng)},southWest:{lat:parseFloat(n.southWest.lat),lng:parseFloat(n.southWest.lng)}}},vu=function(e,t,r){e.defaultRefinement;var n=function(e,t){var r={};for(var n in e)0<=t.indexOf(n)||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}(e,["defaultRefinement"]),i=Kc(n,t,r,"aroundLatLng");if(i)return i;var a=Kc(n,t,r,"configure.aroundLatLng");return a&&du(a)},mu=function(e,t,r){var n,i,a;return Yc(e,(a=t,(i="boundingBox")in(n={})?Object.defineProperty(n,i,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[i]=a,n),r,!0)},gu=kc({displayName:"AlgoliaGeoSearch",getProvidedProps:function(e,t,r){var n,i,a=$c(r,this.context),o=pu(e,t,this.context),s=a&&a._state.insideBoundingBox&&(n=a._state.insideBoundingBox,i=n.split(","),{northEast:{lat:parseFloat(i[0]),lng:parseFloat(i[1])},southWest:{lat:parseFloat(i[2]),lng:parseFloat(i[3])}})||void 0,c=vu(e,t,this.context),u=a&&a._state.aroundLatLng&&du(a._state.aroundLatLng)||void 0,f=o||s,l=c||u;return{hits:a?a.hits.filter(function(e){return Boolean(e._geoloc)}):[],isRefinedWithMap:Boolean(f),currentRefinement:f,position:l}},refine:function(e,t,r){return mu(t,r,this.context)},getSearchParameters:function(e,t,r){var n=pu(t,r,this.context);return n?e.setQueryParameter("insideBoundingBox",lu(n)):e},cleanUp:function(e,t){return Zc(t,this.context,"boundingBox")},getMetadata:function(e,t){var r=this,n=[],i="boundingBox",a=zc(this.context),o={},s=pu(e,t,this.context);return s&&n.push({label:i+": "+lu(s),value:function(e){return mu(e,o,r.context)},currentRefinement:s}),{id:i,index:a,items:n}},shouldComponentUpdate:function(){return!0}}),yu=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};var bu=function(e){return e.attributes[0]},Ru="hierarchicalMenu";function xu(e,t,r){return Kc(e,t,r,Ru+"."+bu(e),null,function(e){return""===e?null:e})}function Fu(e,l,h,d){return e.map(function(e){return{label:e.name,value:(t=e.path,r=l,n=h,i=d,a=r.id,o=r.attributes,s=r.separator,c=r.rootPath,u=r.showParentLevel,f=xu(r,n,i),null===f?t:new Rc({hierarchicalFacets:[{name:a,attributes:o,separator:s,rootPath:c,showParentLevel:u}]}).toggleHierarchicalFacetRefinement(a,f).toggleHierarchicalFacetRefinement(a,t).getHierarchicalRefinement(a)[0]),count:e.count,isRefined:e.isRefined,items:e.data&&Fu(e.data,l,h,d)};var t,r,n,i,a,o,s,c,u,f})}function _u(e,t,r,n){var i,a,o,s=bu(e);return Yc(t,(o=r||"",(a=s)in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,Ru)}var ju=["name:asc"],wu=kc({displayName:"AlgoliaHierarchicalMenu",propTypes:{attributes:function(e,t,r){if(!Array.isArray(e[t])||e[t].some(function(e){return"string"!=typeof e})||e[t].length<1)return new Error("Invalid prop "+t+" supplied to "+r+". Expected an Array of Strings")},separator:M.string,rootPath:M.string,showParentLevel:M.bool,defaultRefinement:M.string,showMore:M.bool,limit:M.number,showMoreLimit:M.number,transformItems:M.func},defaultProps:{showMore:!1,limit:10,showMoreLimit:20,separator:" > ",rootPath:null,showParentLevel:!0},getProvidedProps:function(e,t,r){var n=e.showMore,i=e.limit,a=e.showMoreLimit,o=bu(e),s=$c(r,this.context);if(!(Boolean(s)&&Boolean(s.getFacetByName(o))))return{items:[],currentRefinement:xu(e,t,this.context),canRefine:!1};var c=n?a:i,u=s.getFacetValues(o,{sortBy:ju}),f=u.data?Fu(u.data,e,t,this.context):[],l=e.transformItems?e.transformItems(f):f;return{items:function t(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:[],r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:10;return e.slice(0,r).map(function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(e.items)?yu({},e,{items:t(e.items,r)}):e})}(l,c),currentRefinement:xu(e,t,this.context),canRefine:0<l.length}},refine:function(e,t,r){return _u(e,t,r,this.context)},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,Ru+"."+bu(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attributes,i=t.separator,a=t.rootPath,o=t.showParentLevel,s=t.showMore,c=t.limit,u=t.showMoreLimit,f=bu(t),l=s?u:c;e=e.addHierarchicalFacet({name:f,attributes:n,separator:i,rootPath:a,showParentLevel:o}).setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,l)});var h=xu(t,r,this.context);return null!==h&&(e=e.toggleHierarchicalFacetRefinement(f,h)),e},getMetadata:function(t,e){var r=this,n=t.attributes[0],i=bu(t),a=xu(t,e,this.context);return{id:i,index:zc(this.context),items:a?[{label:n+": "+a,attribute:n,value:function(e){return _u(t,e,"",r.context)},currentRefinement:a}]:[]}}}),Pu=function(e){var t=e.attribute,r=e.hit,n=e.highlightProperty,i=e.preTag,a=void 0===i?wc.highlightPreTag:i,o=e.postTag;return function(e){var t=e.preTag,r=void 0===t?"<em>":t,n=e.postTag,i=void 0===n?"</em>":n,a=e.highlightProperty,o=e.attribute,s=e.hit;if(!s)throw new Error("`hit`, the matching record, must be provided");var c=Br(s[a],o,{});return Array.isArray(c)?c.map(function(e){return Pc({preTag:r,postTag:i,highlightedValue:e.value})}):Pc({preTag:r,postTag:i,highlightedValue:c.value})}({attribute:t,highlightProperty:n,hit:r,preTag:a,postTag:void 0===o?wc.highlightPostTag:o})},Su=kc({displayName:"AlgoliaHighlighter",propTypes:{},getProvidedProps:function(){return{highlight:Pu}}}),Ou=kc({displayName:"AlgoliaHits",getProvidedProps:function(e,t,r){var n=$c(r,this.context);return{hits:n?n.hits:[]}},getSearchParameters:function(e){return e}}),Eu=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};function Tu(e,t,r){return Kc(e,t,r,"hitsPerPage",null,function(e){return"string"==typeof e?parseInt(e,10):e})}var Au=kc({displayName:"AlgoliaHitsPerPage",propTypes:{defaultRefinement:M.number.isRequired,items:M.arrayOf(M.shape({label:M.string,value:M.number.isRequired})).isRequired,transformItems:M.func},getProvidedProps:function(e,t){var r=Tu(e,t,this.context),n=e.items.map(function(e){return e.value===r?Eu({},e,{isRefined:!0}):Eu({},e,{isRefined:!1})});return{items:e.transformItems?e.transformItems(n):n,currentRefinement:r}},refine:function(e,t,r){var n,i,a;return Yc(t,(a=r,(i="hitsPerPage")in(n={})?Object.defineProperty(n,i,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[i]=a,n),this.context,!0)},cleanUp:function(e,t){return Zc(t,this.context,"hitsPerPage")},getSearchParameters:function(e,t,r){return e.setHitsPerPage(Tu(t,r,this.context))},getMetadata:function(){return{id:"hitsPerPage"}}});function Nu(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)}function Cu(e,t,r){return Kc(e,t,r,"page",1,function(e){return"string"==typeof e&&(e=parseInt(e,10)),e})}var Iu=kc({displayName:"AlgoliaInfiniteHits",getProvidedProps:function(e,t,r){var n=$c(r,this.context);if(this._allResults=this._allResults||[],this._previousPage=this._previousPage||0,!n)return{hits:[],hasMore:!1};var i=n.hits,a=n.page,o=n.nbPages;0===a?this._allResults=i:a>this._previousPage?this._allResults=[].concat(Nu(this._allResults),Nu(i)):a<this._previousPage&&(this._allResults=i);var s=a<o-1;return this._previousPage=a,{hits:this._allResults,hasMore:s}},getSearchParameters:function(e,t,r){return e.setQueryParameters({page:Cu(t,r,this.context)-1})},refine:function(e,t){var r,n,i,a=Cu(e,t,this.context)+1;return Yc(t,(i=a,(n="page")in(r={})?Object.defineProperty(r,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[n]=i,r),this.context,!1)}});var Hu="menu";function Qu(e){return e.attribute}function Mu(e,t,r){return Kc(e,t,r,Hu+"."+Qu(e),null,function(e){return""===e?null:e})}function Du(e,t,r,n){return e===Mu(t,r,n)?"":e}function Bu(e){var t=e.showMore,r=e.limit,n=e.showMoreLimit;return t?n:r}function Lu(e,t,r,n){var i,a,o,s=Qu(e);return Yc(t,(o=r||"",(a=s)in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,Hu)}var ku=["count:desc","name:asc"],Uu=kc({displayName:"AlgoliaMenu",propTypes:{attribute:M.string.isRequired,showMore:M.bool,limit:M.number,showMoreLimit:M.number,defaultRefinement:M.string,transformItems:M.func,searchable:M.bool},defaultProps:{showMore:!1,limit:10,showMoreLimit:20},getProvidedProps:function(t,r,e,n,i){var a=this,o=t.attribute,s=t.searchable,c=$c(e,this.context),u=Boolean(c)&&Boolean(c.getFacetByName(o)),f=Boolean(i&&i[o]&&""!==i.query);if(s&&this.context.multiIndexContext)throw new Error("react-instantsearch: searching in *List is not available when used inside a multi index context");if(!u)return{items:[],currentRefinement:Mu(t,r,this.context),isFromSearch:f,searchable:s,canRefine:u};var l=f?i[o].map(function(e){return{label:e.value,value:Du(e.value,t,r,a.context),_highlightResult:{label:{value:e.highlighted}},count:e.count,isRefined:e.isRefined}}):c.getFacetValues(o,{sortBy:ku}).map(function(e){return{label:e.name,value:Du(e.name,t,r,a.context),count:e.count,isRefined:e.isRefined}}),h=s&&!f?ro(l,["isRefined","count","label"],["desc","desc","asc"]):l,d=t.transformItems?t.transformItems(h):h;return{items:d.slice(0,Bu(t)),currentRefinement:Mu(t,r,this.context),isFromSearch:f,searchable:s,canRefine:0<d.length}},refine:function(e,t,r){return Lu(e,t,r,this.context)},searchForFacetValues:function(e,t,r){return{facetName:e.attribute,query:r,maxFacetHits:Bu(e)}},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,Hu+"."+Qu(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attribute;e=(e=e.setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,Bu(t))})).addDisjunctiveFacet(n);var i=Mu(t,r,this.context);return null!==i&&(e=e.addDisjunctiveFacetRefinement(n,i)),e},getMetadata:function(t,e){var r=this,n=Qu(t),i=Mu(t,e,this.context);return{id:n,index:zc(this.context),items:null===i?[]:[{label:t.attribute+": "+i,attribute:t.attribute,value:function(e){return Lu(t,e,"",r.context)},currentRefinement:i}]}}}),Vu=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=e[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")};function qu(e){return void 0===e.start&&void 0===e.end?"":(e.start?e.start:"")+":"+(e.end?e.end:"")}var Wu="multiRange";function zu(e){return e.attribute}function $u(e,t,r){return Kc(e,t,r,Wu+"."+zu(e),"",function(e){return""===e?"":e})}function Ju(e,t,r,n){var i,a,o;return Yc(t,(i={},a=zu(e),o=r,a in i?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,Wu)}var Yu=kc({displayName:"AlgoliaNumericMenu",propTypes:{id:M.string,attribute:M.string.isRequired,items:M.arrayOf(M.shape({label:M.node,start:M.number,end:M.number})).isRequired,transformItems:M.func},getProvidedProps:function(v,e,t){var r=v.attribute,m=$u(v,e,this.context),g=$c(t,this.context),n=v.items.map(function(e){var t,r,n,i,a,o,s,c,u,f,l,h,d,p=qu(e);return{label:e.label,value:p,isRefined:p===m,noRefinement:!!g&&(t=zu(v),r=g,n=p,f=r.getFacetByName(t)?r.getFacetStats(t):null,l=n.split(":"),h=0===Number(l[0])||""===n?Number.NEGATIVE_INFINITY:Number(l[0]),d=0===Number(l[1])||""===n?Number.POSITIVE_INFINITY:Number(l[1]),!(Boolean(f)&&(c=h,u=d,(s=f).min>c&&s.min<u||s.max>c&&s.max<u||(o=d,(a=h)>(i=f).min&&a<i.max||o>i.min&&o<i.max))))}}),i=g&&g.getFacetByName(r)?g.getFacetStats(r):null,a=cn(n,function(e){return!0===e.isRefined});n.some(function(e){return""===e.value})||n.push({value:"",isRefined:fn(a),noRefinement:!i,label:"All"});var o=v.transformItems?v.transformItems(n):n;return{items:o,currentRefinement:m,canRefine:0<o.length&&o.some(function(e){return!1===e.noRefinement})}},refine:function(e,t,r){return Ju(e,t,r,this.context)},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,Wu+"."+zu(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attribute,i=function(e){if(0===e.length)return{start:null,end:null};var t=e.split(":"),r=Vu(t,2),n=r[0],i=r[1];return{start:0<n.length?parseInt(n,10):null,end:0<i.length?parseInt(i,10):null}}($u(t,r,this.context)),a=i.start,o=i.end;return e=e.addDisjunctiveFacet(n),a&&(e=e.addNumericRefinement(n,">=",a)),o&&(e=e.addNumericRefinement(n,"<=",o)),e},getMetadata:function(t,e){var r=this,n=zu(t),i=$u(t,e,this.context),a=[],o=zc(this.context);if(""!==i){var s=cn(t.items,function(e){return qu(e)===i}).label;a.push({label:t.attribute+": "+s,attribute:t.attribute,currentRefinement:s,value:function(e){return Ju(t,e,"",r.context)}})}return{id:n,index:o,items:a}}});function Gu(e,t,r){return Kc(e,t,r,"page",1,function(e){return"string"==typeof e?parseInt(e,10):e})}function Ku(e,t,r,n){var i,a,o;return Yc(t,(o=r,(a="page")in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!1)}var Zu=kc({displayName:"AlgoliaPagination",getProvidedProps:function(e,t,r){var n=$c(r,this.context);if(!n)return null;var i=n.nbPages;return{nbPages:i,currentRefinement:Gu(e,t,this.context),canRefine:1<i}},refine:function(e,t,r){return Ku(0,t,r,this.context)},cleanUp:function(e,t){return Zc(t,this.context,"page")},getSearchParameters:function(e,t,r){return e.setPage(Gu(t,r,this.context)-1)},getMetadata:function(){return{id:"page"}}}),Xu=kc({displayName:"AlgoliaPoweredBy",propTypes:{},getProvidedProps:function(e){return{url:"https://www.algolia.com/?utm_source=react-instantsearch&utm_medium=website&utm_content="+(e.canRender?location.hostname:"")+"&utm_campaign=poweredby"}}}),ef=ee.isFinite;var tf=function(e){return"number"==typeof e&&ef(e)};function rf(e){return e.attribute}var nf="range";function af(o,e,t,r){var n=Kc(o,e,r,nf+"."+rf(o),{},function(e){var t=e.min,r=e.max,n=Boolean(o.precision),i=t;"string"==typeof i&&(i=n?parseFloat(i):parseInt(i,10));var a=r;return"string"==typeof a&&(a=n?parseFloat(a):parseInt(a,10)),{min:i,max:a}}),i=void 0!==o.min,a=void 0!==o.max,s=void 0!==n.min,c=void 0!==n.max;if(i&&s&&n.min<t.min)throw Error("You can't provide min value lower than range.");if(a&&c&&n.max>t.max)throw Error("You can't provide max value greater than range.");return i&&!s&&(n.min=t.min),a&&!c&&(n.max=t.max),n}function of(e,t){return{min:void 0!==e.min?e.min:t.min,max:void 0!==e.max?e.max:t.max}}function sf(e,t,r,n){return e||r!==n?e&&t?r:n:void 0}function cf(e,t,r,n,i){var a=r.min,o=r.max,s=n.min,c=n.max,u=void 0===a||""===a,f=void 0===o||""===o,l=u?void 0:parseFloat(a),h=f?void 0:parseFloat(o),d=u||tf(l),p=f||tf(h);if(!d||!p)throw Error("You can't provide non finite values to the range connector.");if(l<s)throw Error("You can't provide min value lower than range.");if(c<h)throw Error("You can't provide max value greater than range.");var v,m,g,y=rf(e);return Yc(t,(v={},m=y,g={min:sf(void 0!==e.min,u,s,l),max:sf(void 0!==e.max,f,c,h)},m in v?Object.defineProperty(v,m,{value:g,enumerable:!0,configurable:!0,writable:!0}):v[m]=g,v),i,!0,nf)}var uf=kc({displayName:"AlgoliaRange",propTypes:{id:M.string,attribute:M.string.isRequired,defaultRefinement:M.shape({min:M.number,max:M.number}),min:M.number,max:M.number,precision:M.number,header:M.node,footer:M.node},defaultProps:{precision:0},getProvidedProps:function(e,t,r){var n=e.attribute,i=e.precision,a=e.min,o=e.max,s=$c(r,this.context),c=s&&s.getFacetByName(n),u=c&&s.getFacetStats(n)||{},f=(c?s.getFacetValues(n):[]).map(function(e){return{value:e.name,count:e.count}}),l=function(e,t,r){var n=Math.pow(10,r),i=void 0;i=tf(e.min)?e.min:tf(t.min)?t.min:void 0;var a=void 0;return a=tf(e.max)?e.max:tf(t.max)?t.max:void 0,{min:void 0!==i?Math.floor(i*n)/n:i,max:void 0!==a?Math.ceil(a*n)/n:a}}({min:a,max:o},u,i),h=l.min,d=l.max;this._currentRange={min:h,max:d};var p=af(e,t,this._currentRange,this.context);return{min:h,max:d,canRefine:0<f.length,currentRefinement:of(p,this._currentRange),count:f,precision:i}},refine:function(e,t,r){return cf(e,t,r,this._currentRange,this.context)},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,nf+"."+rf(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attribute,i=af(t,r,this._currentRange,this.context),a=i.min,o=i.max;return e=e.addDisjunctiveFacet(n),void 0!==a&&(e=e.addNumericRefinement(n,">=",a)),void 0!==o&&(e=e.addNumericRefinement(n,"<=",o)),e},getMetadata:function(t,e){var r=this,n=this._currentRange,i=n.min,a=n.max,o=af(t,e,this._currentRange,this.context),s=o.min,c=o.max,u=[],f=void 0!==s,l=void 0!==c;if(f&&s!==i||l&&c!==a){var h=[f?s+" <= ":"",t.attribute,l?" <= "+c:""];u.push({label:h.join(""),attribute:t.attribute,value:function(e){return cf(t,e,{},r._currentRange,r.context)},currentRefinement:of({min:s,max:c},{min:i,max:a})})}return{id:rf(t),index:zc(this.context),items:u}}});var ff="refinementList";function lf(e){return e.attribute}function hf(e,t,r){return Kc(e,t,r,ff+"."+lf(e),[],function(e){return"string"==typeof e?""===e?[]:[e]:e})}function df(t,e,r,n){var i=hf(e,r,n);return-1===i.indexOf(t)?i.concat([t]):i.filter(function(e){return e!==t})}function pf(e){var t=e.showMore,r=e.limit,n=e.showMoreLimit;return t?n:r}function vf(e,t,r,n){var i,a,o,s=lf(e);return Yc(t,(i={},a=s,o=0<r.length?r:"",a in i?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,ff)}var mf=["isRefined","count:desc","name:asc"],gf=kc({displayName:"AlgoliaRefinementList",propTypes:{id:M.string,attribute:M.string.isRequired,operator:M.oneOf(["and","or"]),showMore:M.bool,limit:M.number,showMoreLimit:M.number,defaultRefinement:M.arrayOf(M.oneOfType([M.string,M.number])),searchable:M.bool,transformItems:M.func},defaultProps:{operator:"or",showMore:!1,limit:10,showMoreLimit:20},getProvidedProps:function(t,r,e,n,i){var a=this,o=t.attribute,s=t.searchable,c=$c(e,this.context),u=Boolean(c)&&Boolean(c.getFacetByName(o)),f=Boolean(i&&i[o]&&""!==i.query);if(s&&this.context.multiIndexContext)throw new Error("react-instantsearch: searching in *List is not available when used inside a multi index context");if(!u)return{items:[],currentRefinement:hf(t,r,this.context),canRefine:u,isFromSearch:f,searchable:s};var l=f?i[o].map(function(e){return{label:e.value,value:df(e.value,t,r,a.context),_highlightResult:{label:{value:e.highlighted}},count:e.count,isRefined:e.isRefined}}):c.getFacetValues(o,{sortBy:mf}).map(function(e){return{label:e.name,value:df(e.name,t,r,a.context),count:e.count,isRefined:e.isRefined}}),h=t.transformItems?t.transformItems(l):l;return{items:h.slice(0,pf(t)),currentRefinement:hf(t,r,this.context),isFromSearch:f,searchable:s,canRefine:0<h.length}},refine:function(e,t,r){return vf(e,t,r,this.context)},searchForFacetValues:function(e,t,r){return{facetName:e.attribute,query:r,maxFacetHits:pf(e)}},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,ff+"."+lf(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attribute,i="and"===t.operator?"addFacet":"addDisjunctiveFacet",a=i+"Refinement";return e=(e=e.setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,pf(t))}))[i](n),hf(t,r,this.context).reduce(function(e,t){return e[a](n,t)},e)},getMetadata:function(n,i){var e=lf(n),a=this.context;return{id:e,index:zc(this.context),items:0<hf(n,i,a).length?[{attribute:n.attribute,label:n.attribute+": ",currentRefinement:hf(n,i,a),value:function(e){return vf(n,e,[],a)},items:hf(n,i,a).map(function(r){return{label:""+r,value:function(e){var t=hf(n,e,a).filter(function(e){return e!==r});return vf(n,i,t,a)}}})}]:[]}}}),yf=kc({displayName:"AlgoliaScrollTo",propTypes:{scrollOn:M.string},defaultProps:{scrollOn:"page"},getProvidedProps:function(e,t){var r=e.scrollOn,n=Kc(e,t,this.context,r,null,function(e){return e});if(this._prevSearchState||(this._prevSearchState={}),Jc(this.context)){var i=zc(this.context);t=t.indices?t.indices[i]:{}}var a=Ei(Ei(t,"configure"),r),o=xc(this._prevSearchState,a);return this._prevSearchState=a,{value:n,hasNotChanged:o}}});function bf(e,t,r){return Kc(e,t,r,"query","",function(e){return e||""})}function Rf(e,t,r,n){var i,a,o;return Yc(t,(o=r,(a="query")in(i={})?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0)}var xf=kc({displayName:"AlgoliaSearchBox",propTypes:{defaultRefinement:M.string},getProvidedProps:function(e,t,r){return{currentRefinement:bf(e,t,this.context),isSearchStalled:r.isSearchStalled}},refine:function(e,t,r){return Rf(0,t,r,this.context)},cleanUp:function(e,t){return r=t,n=this.context,Zc(r,n,"query");var r,n},getSearchParameters:function(e,t,r){return e.setQuery(bf(t,r,this.context))},getMetadata:function(e,t){var r=this,n=bf(e,t,this.context);return{id:"query",index:zc(this.context),items:null===n?[]:[{label:"query: "+n,value:function(e){return Rf(0,e,"",r.context)},currentRefinement:n}]}}}),Ff=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};function _f(e,t,r){return Kc(e,t,r,"sortBy",null,function(e){return e||null})}var jf=kc({displayName:"AlgoliaSortBy",propTypes:{defaultRefinement:M.string,items:M.arrayOf(M.shape({label:M.string,value:M.string.isRequired})).isRequired,transformItems:M.func},getProvidedProps:function(e,t){var r=_f(e,t,this.context),n=e.items.map(function(e){return e.value===r?Ff({},e,{isRefined:!0}):Ff({},e,{isRefined:!1})});return{items:e.transformItems?e.transformItems(n):n,currentRefinement:r}},refine:function(e,t,r){var n,i,a;return Yc(t,(a=r,(i="sortBy")in(n={})?Object.defineProperty(n,i,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[i]=a,n),this.context,!0)},cleanUp:function(e,t){return Zc(t,this.context,"sortBy")},getSearchParameters:function(e,t,r){var n=_f(t,r,this.context);return e.setIndex(n)},getMetadata:function(){return{id:"sortBy"}}}),wf=kc({displayName:"AlgoliaStateResults",getProvidedProps:function(e,t,r){return{searchState:t,searchResults:$c(r,this.context),allSearchResults:r.results,searching:r.searching,isSearchStalled:r.isSearchStalled,error:r.error,searchingForFacetValues:r.searchingForFacetValues,props:e}}}),Pf=kc({displayName:"AlgoliaStats",getProvidedProps:function(e,t,r){var n=$c(r,this.context);return n?{nbHits:n.nbHits,processingTimeMS:n.processingTimeMS}:null}});function Sf(e){return e.attribute}var Of="toggle";function Ef(e,t,r){return Kc(e,t,r,Of+"."+Sf(e),!1,function(e){return e||!1})}function Tf(e,t,r,n){var i,a,o,s=Sf(e);return Yc(t,(i={},o=r||!1,(a=s)in i?Object.defineProperty(i,a,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[a]=o,i),n,!0,Of)}var Af=kc({displayName:"AlgoliaToggle",propTypes:{label:M.string.isRequired,attribute:M.string.isRequired,value:M.any.isRequired,filter:M.func,defaultRefinement:M.bool},getProvidedProps:function(e,t,r){var n=e.attribute,i=e.value,a=$c(r,this.context),o=Ef(e,t,this.context),s=a&&a.getFacetByName(n)?a.getFacetValues(n):null,c=s&&s.length?cn(s,function(e){return e.name===i.toString()}):null,u=c&&c.count,f=s&&s.length?s.reduce(function(e,t){return e+t.count},0):null;return{currentRefinement:o,canRefine:o?null!==f&&0<f:null!==u&&0<u,count:{checked:f,unchecked:u}}},refine:function(e,t,r){return Tf(e,t,r,this.context)},cleanUp:function(e,t){return r=e,n=t,i=this.context,Zc(n,i,Of+"."+Sf(r));var r,n,i},getSearchParameters:function(e,t,r){var n=t.attribute,i=t.value,a=t.filter,o=Ef(t,r,this.context),s=e.addDisjunctiveFacet(n);return o&&(s=s.addDisjunctiveFacetRefinement(n,i),a&&(s=a(s))),s},getMetadata:function(t,e){var r=this,n=Sf(t),i=Ef(t,e,this.context),a=[],o=zc(this.context);return i&&a.push({label:t.label,currentRefinement:i,attribute:t.attribute,value:function(e){return Tf(t,e,!1,r.context)}}),{id:n,index:o,items:a}}});e.connectAutoComplete=au,e.connectBreadcrumb=cu,e.connectConfigure=tu,e.connectCurrentRefinements=fu,e.connectGeoSearch=gu,e.connectHierarchicalMenu=wu,e.connectHighlight=Su,e.connectHits=Ou,e.connectHitsPerPage=Au,e.connectInfiniteHits=Iu,e.connectMenu=Uu,e.connectNumericMenu=Yu,e.connectPagination=Zu,e.connectPoweredBy=Xu,e.connectRange=uf,e.connectRefinementList=gf,e.connectScrollTo=yf,e.connectSearchBox=xf,e.connectSortBy=jf,e.connectStateResults=wf,e.connectStats=Pf,e.connectToggleRefinement=Af,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=Connectors.min.js.map
|
examples/js/src/client/index.js | yusinto/universal-hot-reload | import React from 'react';
import { hydrate } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from '../universal/app';
hydrate(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('reactDiv'),
);
|