path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
examples/react-router/src/components/WelcomeComponent.js | stylesuxx/generator-react-webpack-redux | 'use strict';
import React from 'react';
require('styles//Welcome.css');
class WelcomeComponent extends React.Component {
render() {
let welcome = 'Sorry, not logge in.';
if(this.props.login) {
welcome = 'You are logged in';
}
return (
<div className="welcome-component">
{welcome}
</div>
);
}
}
WelcomeComponent.displayName = 'WelcomeComponent';
// Uncomment properties you need
WelcomeComponent.propTypes = {
login: React.PropTypes.bool.isRequired
};
WelcomeComponent.defaultProps = {
login: false
};
export default WelcomeComponent;
|
src/DateTimePickerDate.js | francisPlaymore/react-bootstrap-datetimepicker | import React, { Component, PropTypes } from "react";
import DateTimePickerDays from "./DateTimePickerDays";
import DateTimePickerMonths from "./DateTimePickerMonths";
import DateTimePickerYears from "./DateTimePickerYears";
export default class DateTimePickerDate extends Component {
static propTypes = {
subtractMonth: PropTypes.func.isRequired,
addMonth: PropTypes.func.isRequired,
viewDate: PropTypes.object.isRequired,
selectedDate: PropTypes.object.isRequired,
showToday: PropTypes.bool,
viewMode: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
daysOfWeekDisabled: PropTypes.array,
setSelectedDate: PropTypes.func.isRequired,
subtractYear: PropTypes.func.isRequired,
addYear: PropTypes.func.isRequired,
setViewMonth: PropTypes.func.isRequired,
setViewYear: PropTypes.func.isRequired,
addDecade: PropTypes.func.isRequired,
subtractDecade: PropTypes.func.isRequired,
minDate: PropTypes.object,
maxDate: PropTypes.object
}
constructor(props) {
super(props);
const viewModes = {
"days": {
daysDisplayed: true,
monthsDisplayed: false,
yearsDisplayed: false
},
"months": {
daysDisplayed: false,
monthsDisplayed: true,
yearsDisplayed: false
},
"years": {
daysDisplayed: false,
monthsDisplayed: false,
yearsDisplayed: true
}
};
this.state = viewModes[this.props.viewMode] || viewModes[Object.keys(viewModes)[this.props.viewMode]] || viewModes.days;
}
showMonths = () => {
return this.setState({
daysDisplayed: false,
monthsDisplayed: true
});
}
showYears = () => {
return this.setState({
monthsDisplayed: false,
yearsDisplayed: true
});
}
setViewYear = (e) => {
this.props.setViewYear(e.target.innerHTML);
return this.setState({
yearsDisplayed: false,
monthsDisplayed: true
});
}
setViewMonth = (e) => {
this.props.setViewMonth(e.target.innerHTML);
return this.setState({
monthsDisplayed: false,
daysDisplayed: true
});
}
renderDays = () => {
if (this.state.daysDisplayed) {
return (
<DateTimePickerDays
addMonth={this.props.addMonth}
daysOfWeekDisabled={this.props.daysOfWeekDisabled}
maxDate={this.props.maxDate}
minDate={this.props.minDate}
selectedDate={this.props.selectedDate}
setSelectedDate={this.props.setSelectedDate}
showMonths={this.showMonths}
showToday={this.props.showToday}
subtractMonth={this.props.subtractMonth}
viewDate={this.props.viewDate}
/>
);
} else {
return null;
}
}
renderMonths = () => {
if (this.state.monthsDisplayed) {
return (
<DateTimePickerMonths
addYear={this.props.addYear}
selectedDate={this.props.selectedDate}
setViewMonth={this.setViewMonth}
showYears={this.showYears}
subtractYear={this.props.subtractYear}
viewDate={this.props.viewDate}
/>
);
} else {
return null;
}
}
renderYears = () => {
if (this.state.yearsDisplayed) {
return (
<DateTimePickerYears
addDecade={this.props.addDecade}
selectedDate={this.props.selectedDate}
setViewYear={this.setViewYear}
subtractDecade={this.props.subtractDecade}
viewDate={this.props.viewDate}
/>
);
} else {
return null;
}
}
render() {
return (
<div className="datepicker">
{this.renderDays()}
{this.renderMonths()}
{this.renderYears()}
</div>
);
}
}
|
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js | suxinde2009/actor-platform | import _ from 'lodash';
import Immutable from 'immutable';
import keymirror from 'keymirror';
import React from 'react';
import { Styles, TextField, FlatButton } from 'material-ui';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import ContactStore from 'stores/ContactStore';
import ContactItem from './ContactItem.react';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const STEPS = keymirror({
NAME_INPUT: null,
CONTACTS_SELECTION: null
});
class CreateGroupForm extends React.Component {
static displayName = 'CreateGroupForm'
static childContextTypes = {
muiTheme: React.PropTypes.object
};
state = {
step: STEPS.NAME_INPUT,
selectedUserIds: new Immutable.Set()
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7'
}
});
}
render() {
let stepForm;
switch (this.state.step) {
case STEPS.NAME_INPUT:
stepForm = (
<form className="group-name" onSubmit={this.onNameSubmit}>
<div className="modal-new__body">
<TextField className="login__form__input"
floatingLabelText="Group name"
fullWidth
onChange={this.onNameChange}
value={this.state.name}/>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Add members"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
case STEPS.CONTACTS_SELECTION:
let contactList = _.map(ContactStore.getContacts(), (contact, i) => {
return (
<ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/>
);
});
stepForm = (
<form className="group-members" onSubmit={this.onMembersSubmit}>
<div className="count">{this.state.selectedUserIds.size} Members</div>
<div className="modal-new__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Create group"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
}
return stepForm;
}
onContactToggle = (contact, isSelected) => {
if (isSelected) {
this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)});
} else {
this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)});
}
}
onNameChange = event => {
event.preventDefault();
this.setState({name: event.target.value});
}
onNameSubmit = event => {
event.preventDefault();
if (this.state.name) {
let name = this.state.name.trim();
if (name.length > 0) {
this.setState({step: STEPS.CONTACTS_SELECTION});
}
}
}
onMembersSubmit =event => {
event.preventDefault();
CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS());
}
}
export default CreateGroupForm;
|
src/routes/topicPage/index.js | xugy0926/shuoriyu | import React from 'react';
import TopicPage from './TopicPage';
import fetch from '../../core/fetch';
import { host } from '../../config';
import * as topicService from '../../services/topicService';
export default {
path: '/topic/:tid',
async action(context, {tid}) {
return <TopicPage topicId={tid}/>;
},
};
|
ajax/libs/shariff/1.4.7/shariff.complete.js | magoni/cdnjs |
/*
* shariff - v1.4.5 - 02.12.2014
* https://github.com/heiseonline/shariff
* Copyright (c) 2014 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli
* Licensed under the MIT <http://www.opensource.org/licenses/mit-license.php> license
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
!function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=e.length,n=it.type(e);return"function"===n||it.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(it.isFunction(t))return it.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return it.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ft.test(t))return it.filter(t,e,n);t=it.filter(t,e)}return it.grep(e,function(e){return it.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xt[e]={};return it.each(e.match(bt)||[],function(e,n){t[n]=!0}),t}function a(){ht.addEventListener?(ht.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(ht.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(ht.addEventListener||"load"===event.type||"complete"===ht.readyState)&&(a(),it.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Et,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Nt.test(n)?it.parseJSON(n):n}catch(i){}it.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!it.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(it.acceptData(e)){var i,o,a=it.expando,s=e.nodeType,l=s?it.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||it.guid++:a),l[u]||(l[u]=s?{}:{toJSON:it.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=it.extend(l[u],t):l[u].data=it.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[it.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[it.camelCase(t)])):i=o,i}}function d(e,t,n){if(it.acceptData(e)){var r,i,o=e.nodeType,a=o?it.cache:e,s=o?e[it.expando]:it.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){it.isArray(t)?t=t.concat(it.map(t,it.camelCase)):t in r?t=[t]:(t=it.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!u(r):!it.isEmptyObject(r))return}(n||(delete a[s].data,u(a[s])))&&(o?it.cleanData([e],!0):nt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return ht.activeElement}catch(e){}}function m(e){var t=Ot.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ct?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ct?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||it.nodeName(r,t)?o.push(r):it.merge(o,g(r,t));return void 0===t||t&&it.nodeName(e,t)?it.merge([e],o):o}function v(e){jt.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return it.nodeName(e,"table")&&it.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==it.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Vt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)it._data(n,"globalEval",!t||it._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&it.hasData(e)){var n,r,i,o=it._data(e),a=it._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)it.event.add(t,n,s[n][r])}a.data&&(a.data=it.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!nt.noCloneEvent&&t[it.expando]){i=it._data(t);for(r in i.events)it.removeEvent(t,r,i.handle);t.removeAttribute(it.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),nt.html5Clone&&e.innerHTML&&!it.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&jt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function N(t,n){var r,i=it(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:it.css(i[0],"display");return i.detach(),o}function E(e){var t=ht,n=Zt[e];return n||(n=N(e,t),"none"!==n&&n||(Kt=(Kt||it("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Kt[0].contentWindow||Kt[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Kt.detach()),Zt[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=it._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[a]=it._data(r,"olddisplay",E(r.nodeName)))):(i=At(r),(n&&"none"!==n||!i)&&it._data(r,"olddisplay",i?n:it.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function D(e,t,n){var r=un.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=it.css(e,n+St[o],!0,i)),r?("content"===n&&(a-=it.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(a-=it.css(e,"border"+St[o]+"Width",!0,i))):(a+=it.css(e,"padding"+St[o],!0,i),"padding"!==n&&(a+=it.css(e,"border"+St[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=en(e),a=nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tn(e,t,o),(0>i||null==i)&&(i=e.style[t]),rn.test(i))return i;r=a&&(nt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function _(){return setTimeout(function(){hn=void 0}),hn=it.now()}function q(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=St[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(xn[t]||[]).concat(xn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function O(e,t,n){var r,i,o,a,s,l,u,c,d=this,f={},p=e.style,h=e.nodeType&&At(e),m=it._data(e,"fxshow");n.queue||(s=it._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,it.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],u=it.css(e,"display"),c="none"===u?it._data(e,"olddisplay")||E(e.nodeName):u,"inline"===c&&"none"===it.css(e,"float")&&(nt.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",nt.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],gn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||it.style(e,r)}else u=void 0;if(it.isEmptyObject(f))"inline"===("none"===u?E(e.nodeName):u)&&(p.display=u);else{m?"hidden"in m&&(h=m.hidden):m=it._data(e,"fxshow",{}),o&&(m.hidden=!h),h?it(e).show():d.done(function(){it(e).hide()}),d.done(function(){var t;it._removeData(e,"fxshow");for(t in f)it.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function F(e,t){var n,r,i,o,a;for(n in e)if(r=it.camelCase(n),i=t[r],o=e[n],it.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=it.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=bn.length,s=it.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=hn||_(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:it.extend({},t),opts:it.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:hn||_(),duration:n.duration,tweens:[],createTween:function(t,n){var r=it.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(F(c,u.opts.specialEasing);a>o;o++)if(r=bn[o].call(u,e,c,u.opts))return r;return it.map(c,M,u),it.isFunction(u.opts.start)&&u.opts.start.call(e,u),it.fx.timer(it.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(bt)||[];if(it.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var l;return o[s]=!0,it.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===In;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=it.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&it.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(it.isArray(t))it.each(t,function(t,i){n||Jn.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==it.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return it.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},et=Z.toString,tt=Z.hasOwnProperty,nt={},rt="1.11.1",it=function(e,t){return new it.fn.init(e,t)},ot=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,st=/-([\da-z])/gi,lt=function(e,t){return t.toUpperCase()};it.fn=it.prototype={jquery:rt,constructor:it,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=it.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return it.each(this,e,t)},map:function(e){return this.pushStack(it.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},it.extend=it.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||it.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(it.isPlainObject(n)||(t=it.isArray(n)))?(t?(t=!1,o=e&&it.isArray(e)?e:[]):o=e&&it.isPlainObject(e)?e:{},a[r]=it.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},it.extend({expando:"jQuery"+(rt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===it.type(e)},isArray:Array.isArray||function(e){return"array"===it.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!it.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==it.type(e)||e.nodeType||it.isWindow(e))return!1;try{if(e.constructor&&!tt.call(e,"constructor")&&!tt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(nt.ownLast)for(t in e)return tt.call(e,t);for(t in e);return void 0===t||tt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[et.call(e)]||"object":typeof e},globalEval:function(t){t&&it.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(at,"ms-").replace(st,lt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(ot,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?it.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&l.push(i);return G.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),it.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||it.guid++,r):void 0},now:function(){return+new Date},support:nt}),it.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var ut=function(e){function t(e,t,n,r){var i,o,a,s,l,u,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(q&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=E(e),(d=t.getAttribute("id"))?p=d.replace(xt,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=u.length;l--;)u[l]=p+f(u[l]);h=bt.test(e)&&c(t.parentNode)||t,m=u.join(",")}if(m)try{return Z.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||J)-(~e.sourceIndex||J);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==V&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[P]||(t[P]={}),(s=l[r])&&s[0]===W&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,l),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=g(b,p),i(u,[],s,l),c=u.length;c--;)(d=u[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);o(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=o?tt.call(r,d):f[c])>-1&&(r[u]=!(a[u]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),u=p(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",u),x=W+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){l.push(c);break}u&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=Q.call(l));v=g(v)}Z.apply(l,v),u&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(l)}return u&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,_,q,M,O,F,B,P="sizzle"+-new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V="undefined",J=1<<31,Y={}.hasOwnProperty,G=[],Q=G.pop,K=G.push,Z=G.push,et=G.slice,tt=G.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),dt=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),ft=new RegExp(st),pt=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},mt=/^(?:input|select|textarea|button)$/i,gt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),Tt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(G=et.call(R.childNodes),R.childNodes),G[R.childNodes.length].nodeType}catch(Ct){Z={apply:G.length?function(e,t){K.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:R,r=n.defaultView;return n!==H&&9===n.nodeType&&n.documentElement?(H=n,_=n.documentElement,q=!N(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){L()},!1):r.attachEvent&&r.attachEvent("onunload",function(){L()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return _.appendChild(e).id=P,!n.getElementsByName||!n.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==V&&q){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==V?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==V&&q?t.getElementsByClassName(e):void 0},O=[],M=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&M.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||M.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=vt.test(F=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&i(function(e){w.disconnectedMatch=F.call(e,"div"),F.call(e,"[s!='']:x"),O.push("!=",st)}),M=M.length&&new RegExp(M.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(_.compareDocumentPosition),B=t||vt.test(_.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===R&&B(R,e)?-1:t===n||t.ownerDocument===R&&B(R,t)?1:D?tt.call(D,e)-tt.call(D,t):0:4&r?-1:1)}:function(e,t){if(e===t)return j=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:D?tt.call(D,e)-tt.call(D,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===R?-1:u[i]===R?1:0},n):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(dt,"='$1']"),!(!w.matchesSelector||!q||O&&O.test(n)||M&&M.test(n)))try{var r=F.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&Y.call(T.attrHandle,t.toLowerCase())?n(e,t,!q):void 0;return void 0!==r?r:w.attributes||!q?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ft.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),u=c[e]||[],p=u[0]===W&&u[1],f=u[0]===W&&u[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(u=(t[P]||(t[P]={}))[e])&&u[0]===W)f=u[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pt.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,Tt).toLowerCase(),function(t){var n;do if(n=q?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return gt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=l(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=T.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in T.filter)!(i=ht[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));
if(!r)break}return n?s.length:s?t.error(e):I(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,d=!r&&E(e=u.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&q&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(wt,Tt),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=ht.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((l=T.find[s])&&(r=l(a.matches[0].replace(wt,Tt),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,d))(r,t,!q,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);it.find=ut,it.expr=ut.selectors,it.expr[":"]=it.expr.pseudos,it.unique=ut.uniqueSort,it.text=ut.getText,it.isXMLDoc=ut.isXML,it.contains=ut.contains;var ct=it.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;it.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?it.find.matchesSelector(r,e)?[r]:[]:it.find.matches(e,it.grep(t,function(e){return 1===e.nodeType}))},it.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(it(e).filter(function(){for(t=0;i>t;t++)if(it.contains(r[t],this))return!0}));for(t=0;i>t;t++)it.find(e,r[t],n);return n=this.pushStack(i>1?it.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ct.test(e)?it(e):e||[],!1).length}});var pt,ht=e.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=it.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof it?t[0]:t,it.merge(this,it.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:ht,!0)),dt.test(n[1])&&it.isPlainObject(t))for(n in t)it.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=ht.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=ht,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):it.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(it):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),it.makeArray(e,this))};gt.prototype=it.fn,pt=it(ht);var vt=/^(?:parents|prev(?:Until|All))/,yt={children:!0,contents:!0,next:!0,prev:!0};it.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!it(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),it.fn.extend({has:function(e){var t,n=it(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(it.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ct.test(e)||"string"!=typeof e?it(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&it.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?it.unique(o):o)},index:function(e){return e?"string"==typeof e?it.inArray(this[0],it(e)):it.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(it.unique(it.merge(this.get(),it(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),it.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return it.dir(e,"parentNode")},parentsUntil:function(e,t,n){return it.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return it.dir(e,"nextSibling")},prevAll:function(e){return it.dir(e,"previousSibling")},nextUntil:function(e,t,n){return it.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return it.dir(e,"previousSibling",n)},siblings:function(e){return it.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return it.sibling(e.firstChild)},contents:function(e){return it.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:it.merge([],e.childNodes)}},function(e,t){it.fn[e]=function(n,r){var i=it.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=it.filter(r,i)),this.length>1&&(yt[e]||(i=it.unique(i)),vt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var bt=/\S+/g,xt={};it.Callbacks=function(e){e="string"==typeof e?xt[e]||o(e):it.extend({},e);var t,n,r,i,a,s,l=[],u=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=l.length,t=!0;l&&i>a;a++)if(l[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:d.disable())},d={add:function(){if(l){var r=l.length;!function o(t){it.each(t,function(t,n){var r=it.type(n);"function"===r?e.unique&&d.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&it.each(arguments,function(e,n){for(var r;(r=it.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?it.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||d.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},it.extend({Deferred:function(e){var t=[["resolve","done",it.Callbacks("once memory"),"resolved"],["reject","fail",it.Callbacks("once memory"),"rejected"],["notify","progress",it.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return it.Deferred(function(n){it.each(t,function(t,o){var a=it.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&it.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?it.extend(e,r):r}},i={};return r.pipe=r.then,it.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&it.isFunction(e.promise)?a:0,l=1===s?e:it.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&it.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var wt;it.fn.ready=function(e){return it.ready.promise().done(e),this},it.extend({isReady:!1,readyWait:1,holdReady:function(e){e?it.readyWait++:it.ready(!0)},ready:function(e){if(e===!0?!--it.readyWait:!it.isReady){if(!ht.body)return setTimeout(it.ready);it.isReady=!0,e!==!0&&--it.readyWait>0||(wt.resolveWith(ht,[it]),it.fn.triggerHandler&&(it(ht).triggerHandler("ready"),it(ht).off("ready")))}}}),it.ready.promise=function(t){if(!wt)if(wt=it.Deferred(),"complete"===ht.readyState)setTimeout(it.ready);else if(ht.addEventListener)ht.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{ht.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&ht.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!it.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),it.ready()}}()}return wt.promise(t)};var Tt,Ct="undefined";for(Tt in it(nt))break;nt.ownLast="0"!==Tt,nt.inlineBlockNeedsLayout=!1,it(function(){var e,t,n,r;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",nt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=ht.createElement("div");if(null==nt.deleteExpando){nt.deleteExpando=!0;try{delete e.test}catch(t){nt.deleteExpando=!1}}e=null}(),it.acceptData=function(e){var t=it.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Nt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Et=/([A-Z])/g;it.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?it.cache[e[it.expando]]:e[it.expando],!!e&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),it.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=it.data(o),1===o.nodeType&&!it._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=it.camelCase(r.slice(5)),l(o,r,i[r])));it._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){it.data(this,e)}):arguments.length>1?this.each(function(){it.data(this,e,t)}):o?l(o,e,it.data(o,e)):void 0},removeData:function(e){return this.each(function(){it.removeData(this,e)})}}),it.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=it._data(e,t),n&&(!r||it.isArray(n)?r=it._data(e,t,it.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=it.queue(e,t),r=n.length,i=n.shift(),o=it._queueHooks(e,t),a=function(){it.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return it._data(e,n)||it._data(e,n,{empty:it.Callbacks("once memory").add(function(){it._removeData(e,t+"queue"),it._removeData(e,n)})})}}),it.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?it.queue(this[0],e):void 0===t?this:this.each(function(){var n=it.queue(this,e,t);it._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&it.dequeue(this,e)})},dequeue:function(e){return this.each(function(){it.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=it.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=it._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var kt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,St=["Top","Right","Bottom","Left"],At=function(e,t){return e=t||e,"none"===it.css(e,"display")||!it.contains(e.ownerDocument,e)},Dt=it.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===it.type(n)){i=!0;for(s in n)it.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,it.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(it(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},jt=/^(?:checkbox|radio)$/i;!function(){var e=ht.createElement("input"),t=ht.createElement("div"),n=ht.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",nt.leadingWhitespace=3===t.firstChild.nodeType,nt.tbody=!t.getElementsByTagName("tbody").length,nt.htmlSerialize=!!t.getElementsByTagName("link").length,nt.html5Clone="<:nav></:nav>"!==ht.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),nt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",nt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",nt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,nt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){nt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==nt.deleteExpando){nt.deleteExpando=!0;try{delete t.test}catch(r){nt.deleteExpando=!1}}}(),function(){var t,n,r=ht.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(nt[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),nt[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Lt=/^(?:input|select|textarea)$/i,Ht=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,qt=/^(?:focusinfocus|focusoutblur)$/,Mt=/^([^.]*)(?:\.(.+)|)$/;it.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it._data(e);if(g){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=it.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof it===Ct||e&&it.event.triggered===e.type?void 0:it.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(bt)||[""],s=t.length;s--;)o=Mt.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(u=it.event.special[p]||{},p=(i?u.delegateType:u.bindType)||p,u=it.event.special[p]||{},d=it.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&it.expr.match.needsContext.test(i),namespace:h.join(".")},l),(f=a[p])||(f=a[p]=[],f.delegateCount=0,u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),it.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it.hasData(e)&&it._data(e);if(g&&(c=g.events)){for(t=(t||"").match(bt)||[""],u=t.length;u--;)if(s=Mt.exec(t[u])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=it.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));l&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||it.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)it.event.remove(e,p+t[u],n,r,!0);it.isEmptyObject(c)&&(delete g.handle,it._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,l,u,c,d,f=[r||ht],p=tt.call(t,"type")?t.type:t,h=tt.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||ht,3!==r.nodeType&&8!==r.nodeType&&!qt.test(p+it.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[it.expando]?t:new it.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:it.makeArray(n,[t]),u=it.event.special[p]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!it.isWindow(r)){for(l=u.delegateType||p,qt.test(l+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||ht)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||p,o=(it._data(s,"events")||{})[t.type]&&it._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&it.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(f.pop(),n)===!1)&&it.acceptData(r)&&a&&r[p]&&!it.isWindow(r)){c=r[a],c&&(r[a]=null),it.event.triggered=p;try{r[p]()}catch(m){}it.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=it.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(it._data(this,"events")||{})[e.type]||[],u=it.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=it.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((it.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?it(n,this).index(l)>=0:it.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[it.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=_t.test(i)?this.mouseHooks:Ht.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new it.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||ht),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ht,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return it.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return it.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=it.extend(new it.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?it.event.trigger(i,null,t):it.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},it.removeEvent=ht.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===Ct&&(e[r]=null),e.detachEvent(r,n))},it.Event=function(e,t){return this instanceof it.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&it.extend(this,t),this.timeStamp=e&&e.timeStamp||it.now(),void(this[it.expando]=!0)):new it.Event(e,t)},it.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},it.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){it.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!it.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),nt.submitBubbles||(it.event.special.submit={setup:function(){return it.nodeName(this,"form")?!1:void it.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=it.nodeName(t,"input")||it.nodeName(t,"button")?t.form:void 0;n&&!it._data(n,"submitBubbles")&&(it.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),it._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&it.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return it.nodeName(this,"form")?!1:void it.event.remove(this,"._submit")}}),nt.changeBubbles||(it.event.special.change={setup:function(){return Lt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(it.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),it.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),it.event.simulate("change",this,e,!0)})),!1):void it.event.add(this,"beforeactivate._change",function(e){var t=e.target;Lt.test(t.nodeName)&&!it._data(t,"changeBubbles")&&(it.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||it.event.simulate("change",this.parentNode,e,!0)}),it._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return it.event.remove(this,"._change"),!Lt.test(this.nodeName)}}),nt.focusinBubbles||it.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){it.event.simulate(t,e.target,it.event.fix(e),!0)};it.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=it._data(r,t);i||r.addEventListener(e,n,!0),it._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=it._data(r,t)-1;i?it._data(r,t,i):(r.removeEventListener(e,n,!0),it._removeData(r,t))}}}),it.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return it().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=it.guid++)),this.each(function(){it.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,it(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){it.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){it.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?it.event.trigger(e,t,n,!0):void 0}});var Ot="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ft=/ jQuery\d+="(?:null|\d+)"/g,Bt=new RegExp("<(?:"+Ot+")[\\s/>]","i"),Pt=/^\s+/,Rt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Wt=/<([\w:]+)/,$t=/<tbody/i,zt=/<|&#?\w+;/,It=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Ut=/^$|\/(?:java|ecma)script/i,Vt=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:nt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Gt=m(ht),Qt=Gt.appendChild(ht.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,it.extend({clone:function(e,t,n){var r,i,o,a,s,l=it.contains(e.ownerDocument,e);if(nt.html5Clone||it.isXMLDoc(e)||!Bt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(nt.noCloneEvent&&nt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||it.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!l&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===it.type(o))it.merge(p,o.nodeType?[o]:o);else if(zt.test(o)){for(s=s||f.appendChild(t.createElement("div")),l=(Wt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(Rt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!nt.leadingWhitespace&&Pt.test(o)&&p.push(t.createTextNode(Pt.exec(o)[0])),!nt.tbody)for(o="table"!==l||$t.test(o)?"<table>"!==c[1]||$t.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)it.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(it.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),nt.appendChecked||it.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===it.inArray(o,r))&&(a=it.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ut.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=it.expando,l=it.cache,u=nt.deleteExpando,c=it.event.special;null!=(n=e[a]);a++)if((t||it.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?it.event.remove(n,r):it.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Ct?n.removeAttribute(s):n[s]=null,J.push(i))}}}),it.fn.extend({text:function(e){return Dt(this,function(e){return void 0===e?it.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ht).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?it.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||it.cleanData(g(n)),n.parentNode&&(t&&it.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&it.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&it.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return it.clone(this,e,t)})},html:function(e){return Dt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Ft,""):void 0;if(!("string"!=typeof e||It.test(e)||!nt.htmlSerialize&&Bt.test(e)||!nt.leadingWhitespace&&Pt.test(e)||Yt[(Wt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Rt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(it.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,it.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,d=u-1,f=e[0],p=it.isFunction(f);if(p||u>1&&"string"==typeof f&&!nt.checkClone&&Xt.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=it.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=it.map(g(s,"script"),b),i=o.length;u>l;l++)r=s,l!==d&&(r=it.clone(r,!0,!0),i&&it.merge(o,g(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,it.map(o,x),l=0;i>l;l++)r=o[l],Ut.test(r.type||"")&&!it._data(r,"globalEval")&&it.contains(a,r)&&(r.src?it._evalUrl&&it._evalUrl(r.src):it.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),it.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){it.fn[e]=function(e){for(var n,r=0,i=[],o=it(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),it(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Kt,Zt={};!function(){var e;nt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=ht.getElementsByTagName("body")[0],n&&n.style?(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ht.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var en,tn,nn=/^margin/,rn=new RegExp("^("+kt+")(?!px)[a-z%]+$","i"),on=/^(top|right|bottom|left)$/;e.getComputedStyle?(en=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||it.contains(e.ownerDocument,e)||(a=it.style(e,t)),rn.test(a)&&nn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):ht.documentElement.currentStyle&&(en=function(e){return e.currentStyle
},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rn.test(a)&&!on.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(ht.createElement("div")),i.style.cssText=t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",t.style.width="1px",l=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=ht.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",nt.opacity="0.5"===r.opacity,nt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",nt.clearCloneStyle="content-box"===n.style.backgroundClip,nt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,it.extend(nt,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==l&&t(),l}}))}(),it.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var an=/alpha\([^)]*\)/i,sn=/opacity\s*=\s*([^)]*)/,ln=/^(none|table(?!-c[ea]).+)/,un=new RegExp("^("+kt+")(.*)$","i"),cn=new RegExp("^([+-])=("+kt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},fn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];it.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":nt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=it.camelCase(t),l=e.style;if(t=it.cssProps[s]||(it.cssProps[s]=S(l,s)),a=it.cssHooks[t]||it.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=cn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(it.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||it.cssNumber[s]||(n+="px"),nt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=it.camelCase(t);return t=it.cssProps[s]||(it.cssProps[s]=S(e.style,s)),a=it.cssHooks[t]||it.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tn(e,t,r)),"normal"===o&&t in fn&&(o=fn[t]),""===n||n?(i=parseFloat(o),n===!0||it.isNumeric(i)?i||0:o):o}}),it.each(["height","width"],function(e,t){it.cssHooks[t]={get:function(e,n,r){return n?ln.test(it.css(e,"display"))&&0===e.offsetWidth?it.swap(e,dn,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&en(e);return D(e,n,r?j(e,t,r,nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,i),i):0)}}}),nt.opacity||(it.cssHooks.opacity={get:function(e,t){return sn.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=it.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===it.trim(o.replace(an,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=an.test(o)?o.replace(an,i):o+" "+i)}}),it.cssHooks.marginRight=k(nt.reliableMarginRight,function(e,t){return t?it.swap(e,{display:"inline-block"},tn,[e,"marginRight"]):void 0}),it.each({margin:"",padding:"",border:"Width"},function(e,t){it.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+St[r]+t]=o[r]||o[r-2]||o[0];return i}},nn.test(e)||(it.cssHooks[e+t].set=D)}),it.fn.extend({css:function(e,t){return Dt(this,function(e,t,n){var r,i,o={},a=0;if(it.isArray(t)){for(r=en(e),i=t.length;i>a;a++)o[t[a]]=it.css(e,t[a],!1,r);return o}return void 0!==n?it.style(e,t,n):it.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){At(this)?it(this).show():it(this).hide()})}}),it.Tween=H,H.prototype={constructor:H,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(it.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.pos=t=this.options.duration?it.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=it.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){it.fx.step[e.prop]?it.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[it.cssProps[e.prop]]||it.cssHooks[e.prop])?it.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},it.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},it.fx=H.prototype.init,it.fx.step={};var hn,mn,gn=/^(?:toggle|show|hide)$/,vn=new RegExp("^(?:([+-])=|)("+kt+")([a-z%]*)$","i"),yn=/queueHooks$/,bn=[O],xn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=vn.exec(t),o=i&&i[3]||(it.cssNumber[e]?"":"px"),a=(it.cssNumber[e]||"px"!==o&&+r)&&vn.exec(it.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,it.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};it.Animation=it.extend(B,{tweener:function(e,t){it.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],xn[n]=xn[n]||[],xn[n].unshift(t)},prefilter:function(e,t){t?bn.unshift(e):bn.push(e)}}),it.speed=function(e,t,n){var r=e&&"object"==typeof e?it.extend({},e):{complete:n||!n&&t||it.isFunction(e)&&e,duration:e,easing:n&&t||t&&!it.isFunction(t)&&t};return r.duration=it.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in it.fx.speeds?it.fx.speeds[r.duration]:it.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){it.isFunction(r.old)&&r.old.call(this),r.queue&&it.dequeue(this,r.queue)},r},it.fn.extend({fadeTo:function(e,t,n,r){return this.filter(At).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=it.isEmptyObject(e),o=it.speed(t,n,r),a=function(){var t=B(this,it.extend({},e),o);(i||it._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=it.timers,a=it._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&yn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&it.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=it._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=it.timers,a=r?r.length:0;for(n.finish=!0,it.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),it.each(["toggle","show","hide"],function(e,t){var n=it.fn[t];it.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(q(t,!0),e,r,i)}}),it.each({slideDown:q("show"),slideUp:q("hide"),slideToggle:q("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){it.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),it.timers=[],it.fx.tick=function(){var e,t=it.timers,n=0;for(hn=it.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||it.fx.stop(),hn=void 0},it.fx.timer=function(e){it.timers.push(e),e()?it.fx.start():it.timers.pop()},it.fx.interval=13,it.fx.start=function(){mn||(mn=setInterval(it.fx.tick,it.fx.interval))},it.fx.stop=function(){clearInterval(mn),mn=null},it.fx.speeds={slow:600,fast:200,_default:400},it.fn.delay=function(e,t){return e=it.fx?it.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=ht.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=ht.createElement("select"),i=n.appendChild(ht.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",nt.getSetAttribute="t"!==t.className,nt.style=/top/.test(r.getAttribute("style")),nt.hrefNormalized="/a"===r.getAttribute("href"),nt.checkOn=!!e.value,nt.optSelected=i.selected,nt.enctype=!!ht.createElement("form").enctype,n.disabled=!0,nt.optDisabled=!i.disabled,e=ht.createElement("input"),e.setAttribute("value",""),nt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),nt.radioValue="t"===e.value}();var wn=/\r/g;it.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=it.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,it(this).val()):e,null==i?i="":"number"==typeof i?i+="":it.isArray(i)&&(i=it.map(i,function(e){return null==e?"":e+""})),t=it.valHooks[this.type]||it.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=it.valHooks[i.type]||it.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(wn,""):null==n?"":n)}}}),it.extend({valHooks:{option:{get:function(e){var t=it.find.attr(e,"value");return null!=t?t:it.trim(it.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(nt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&it.nodeName(n.parentNode,"optgroup"))){if(t=it(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=it.makeArray(t),a=i.length;a--;)if(r=i[a],it.inArray(it.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),it.each(["radio","checkbox"],function(){it.valHooks[this]={set:function(e,t){return it.isArray(t)?e.checked=it.inArray(it(e).val(),t)>=0:void 0}},nt.checkOn||(it.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tn,Cn,Nn=it.expr.attrHandle,En=/^(?:checked|selected)$/i,kn=nt.getSetAttribute,Sn=nt.input;it.fn.extend({attr:function(e,t){return Dt(this,it.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){it.removeAttr(this,e)})}}),it.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ct?it.prop(e,t,n):(1===o&&it.isXMLDoc(e)||(t=t.toLowerCase(),r=it.attrHooks[t]||(it.expr.match.bool.test(t)?Cn:Tn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=it.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void it.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(bt);if(o&&1===e.nodeType)for(;n=o[i++];)r=it.propFix[n]||n,it.expr.match.bool.test(n)?Sn&&kn||!En.test(n)?e[r]=!1:e[it.camelCase("default-"+n)]=e[r]=!1:it.attr(e,n,""),e.removeAttribute(kn?n:r)},attrHooks:{type:{set:function(e,t){if(!nt.radioValue&&"radio"===t&&it.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Cn={set:function(e,t,n){return t===!1?it.removeAttr(e,n):Sn&&kn||!En.test(n)?e.setAttribute(!kn&&it.propFix[n]||n,n):e[it.camelCase("default-"+n)]=e[n]=!0,n}},it.each(it.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Nn[t]||it.find.attr;Nn[t]=Sn&&kn||!En.test(t)?function(e,t,r){var i,o;return r||(o=Nn[t],Nn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Nn[t]=o),i}:function(e,t,n){return n?void 0:e[it.camelCase("default-"+t)]?t.toLowerCase():null}}),Sn&&kn||(it.attrHooks.value={set:function(e,t,n){return it.nodeName(e,"input")?void(e.defaultValue=t):Tn&&Tn.set(e,t,n)}}),kn||(Tn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Nn.id=Nn.name=Nn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},it.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Tn.set},it.attrHooks.contenteditable={set:function(e,t,n){Tn.set(e,""===t?!1:t,n)}},it.each(["width","height"],function(e,t){it.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),nt.style||(it.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var An=/^(?:input|select|textarea|button|object)$/i,Dn=/^(?:a|area)$/i;it.fn.extend({prop:function(e,t){return Dt(this,it.prop,e,t,arguments.length>1)},removeProp:function(e){return e=it.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),it.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!it.isXMLDoc(e),o&&(t=it.propFix[t]||t,i=it.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=it.find.attr(e,"tabindex");return t?parseInt(t,10):An.test(e.nodeName)||Dn.test(e.nodeName)&&e.href?0:-1}}}}),nt.hrefNormalized||it.each(["href","src"],function(e,t){it.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),nt.optSelected||(it.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),it.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){it.propFix[this.toLowerCase()]=this}),nt.enctype||(it.propFix.enctype="encoding");var jn=/[\t\r\n\f]/g;it.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=it.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?it.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(it.isFunction(e)?function(n){it(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=it(this),o=e.match(bt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ct||"boolean"===n)&&(this.className&&it._data(this,"__className__",this.className),this.className=this.className||e===!1?"":it._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(jn," ").indexOf(t)>=0)return!0;return!1}}),it.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){it.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),it.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var Ln=it.now(),Hn=/\?/,_n=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;it.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=it.trim(t+"");return i&&!it.trim(i.replace(_n,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():it.error("Invalid JSON: "+t)},it.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||it.error("Invalid XML: "+t),n};var qn,Mn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Bn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Pn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Rn=/^(?:GET|HEAD)$/,Wn=/^\/\//,$n=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,zn={},In={},Xn="*/".concat("*");try{Mn=location.href}catch(Un){Mn=ht.createElement("a"),Mn.href="",Mn=Mn.href}qn=$n.exec(Mn.toLowerCase())||[],it.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mn,type:"GET",isLocal:Pn.test(qn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":it.parseJSON,"text xml":it.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,it.ajaxSettings),t):W(it.ajaxSettings,e)},ajaxPrefilter:P(zn),ajaxTransport:P(In),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(it.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(it.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,l&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),l&&(p.trigger("ajaxComplete",[w,d]),--it.active||it.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,d=it.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?it(f):it.event,h=it.Deferred(),m=it.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Bn.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||Mn)+"").replace(On,"").replace(Wn,qn[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=it.trim(d.dataType||"*").toLowerCase().match(bt)||[""],null==d.crossDomain&&(r=$n.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qn[1]&&r[2]===qn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qn[3]||("http:"===qn[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=it.param(d.data,d.traditional)),R(zn,d,t,w),2===b)return w;l=d.global,l&&0===it.active++&&it.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Rn.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Hn.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Fn.test(o)?o.replace(Fn,"$1_="+Ln++):o+(Hn.test(o)?"&":"?")+"_="+Ln++)),d.ifModified&&(it.lastModified[o]&&w.setRequestHeader("If-Modified-Since",it.lastModified[o]),it.etag[o]&&w.setRequestHeader("If-None-Match",it.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Xn+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(u=R(In,d,t,w)){w.readyState=1,l&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,u.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return it.get(e,t,n,"json")},getScript:function(e,t){return it.get(e,void 0,t,"script")}}),it.each(["get","post"],function(e,t){it[t]=function(e,n,r,i){return it.isFunction(n)&&(i=i||r,r=n,n=void 0),it.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),it.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){it.fn[t]=function(e){return this.on(t,e)}}),it._evalUrl=function(e){return it.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},it.fn.extend({wrapAll:function(e){if(it.isFunction(e))return this.each(function(t){it(this).wrapAll(e.call(this,t))});if(this[0]){var t=it(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(it.isFunction(e)?function(t){it(this).wrapInner(e.call(this,t))}:function(){var t=it(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=it.isFunction(e);return this.each(function(n){it(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){it.nodeName(this,"body")||it(this).replaceWith(this.childNodes)}).end()}}),it.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!nt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||it.css(e,"display"))},it.expr.filters.visible=function(e){return!it.expr.filters.hidden(e)};var Vn=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Gn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;it.param=function(e,t){var n,r=[],i=function(e,t){t=it.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=it.ajaxSettings&&it.ajaxSettings.traditional),it.isArray(e)||e.jquery&&!it.isPlainObject(e))it.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Vn,"+")},it.fn.extend({serialize:function(){return it.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=it.prop(this,"elements");return e?it.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!it(this).is(":disabled")&&Qn.test(this.nodeName)&&!Gn.test(e)&&(this.checked||!jt.test(e))}).map(function(e,t){var n=it(this).val();return null==n?null:it.isArray(n)?it.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),it.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Kn=0,Zn={},er=it.ajaxSettings.xhr();e.ActiveXObject&&it(e).on("unload",function(){for(var e in Zn)Zn[e](void 0,!0)}),nt.cors=!!er&&"withCredentials"in er,er=nt.ajax=!!er,er&&it.ajaxTransport(function(e){if(!e.crossDomain||nt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Kn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete Zn[a],t=void 0,o.onreadystatechange=it.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Zn[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),it.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return it.globalEval(e),e}}}),it.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),it.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=ht.head||it("head")[0]||ht.documentElement;return{send:function(r,i){t=ht.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],nr=/(=)\?(?=&|$)|\?\?/;it.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||it.expando+"_"+Ln++;return this[e]=!0,e}}),it.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(nr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&nr.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=it.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(nr,"$1"+i):t.jsonp!==!1&&(t.url+=(Hn.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||it.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,tr.push(i)),a&&it.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),it.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||ht;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=it.buildFragment([e],t,i),i&&i.length&&it(i).remove(),it.merge([],r.childNodes))};var rr=it.fn.load;it.fn.load=function(e,t,n){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=it.trim(e.slice(s,e.length)),e=e.slice(0,s)),it.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&it.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?it("<div>").append(it.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},it.expr.filters.animated=function(e){return it.grep(it.timers,function(t){return e===t.elem}).length};var ir=e.document.documentElement;it.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=it.css(e,"position"),d=it(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=it.css(e,"top"),l=it.css(e,"left"),u=("absolute"===c||"fixed"===c)&&it.inArray("auto",[o,l])>-1,u?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),it.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},it.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){it.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,it.contains(t,i)?(typeof i.getBoundingClientRect!==Ct&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===it.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),it.nodeName(e[0],"html")||(n=e.offset()),n.top+=it.css(e[0],"borderTopWidth",!0),n.left+=it.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-it.css(r,"marginTop",!0),left:t.left-n.left-it.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||ir;e&&!it.nodeName(e,"html")&&"static"===it.css(e,"position");)e=e.offsetParent;return e||ir})}}),it.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);it.fn[e]=function(r){return Dt(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?it(o).scrollLeft():i,n?i:it(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),it.each(["top","left"],function(e,t){it.cssHooks[t]=k(nt.pixelPosition,function(e,n){return n?(n=tn(e,t),rn.test(n)?it(e).position()[t]+"px":n):void 0})}),it.each({Height:"height",Width:"width"},function(e,t){it.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){it.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Dt(this,function(t,n,r){var i;return it.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?it.css(t,n,a):it.style(t,n,r,a)
},t,o?r:void 0,o,null)}})}),it.fn.size=function(){return this.length},it.fn.andSelf=it.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return it});var or=e.jQuery,ar=e.$;return it.noConflict=function(t){return e.$===it&&(e.$=ar),t&&e.jQuery===it&&(e.jQuery=or),it},typeof t===Ct&&(e.jQuery=e.$=it),it});
},{}],2:[function(require,module,exports){
"use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share"},name:"facebook",title:{de:"Bei Facebook teilen",en:"Share on Facebook"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+r+e.getReferrerTrack()}};
},{}],3:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!0,shareText:"+1",name:"googleplus",title:{de:"Bei Google+ teilen",en:"Share on Google+"},shareUrl:"https://plus.google.com/share?url="+e.getURL()+e.getReferrerTrack()}};
},{}],4:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"Info",name:"info",title:{de:"weitere Informationen",en:"more information"},shareUrl:e.getInfoUrl()}};
},{}],5:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"mail",name:"mail",title:{de:"Per E-Mail versenden",en:"Send by email"},shareUrl:e.getURL()+"?view=mail"}};
},{}],6:[function(require,module,exports){
"use strict";var $=require("jquery");module.exports=function(e){return{popup:!0,shareText:"tweet",name:"twitter",title:{de:"Bei Twitter teilen",en:"Share on Twitter"},shareUrl:"https://twitter.com/intent/tweet?text="+e.getShareText()+"&url="+e.getURL()+e.getReferrerTrack()}};
},{"jquery":1}],7:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"WhatsApp",name:"whatsapp",title:{de:"Bei Whatsapp teilen",en:"Share on Whatsapp"},shareUrl:"whatsapp://send?text="+e.getShareText()+"%20"+e.getURL()+e.getReferrerTrack()}};
},{}],8:[function(require,module,exports){
(function (global){
"use strict";var $=require("jquery"),_Shariff=function(t,e){var r=this;this.element=t,this.options=$.extend({},this.defaults,e,$(t).data());var n=[require("./services/facebook"),require("./services/googleplus"),require("./services/twitter"),require("./services/whatsapp"),require("./services/mail"),require("./services/info")];this.services=$.map(this.options.services,function(t){var e;return n.forEach(function(n){return n=n(r),n.name===t?(e=n,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};_Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://ct.de/-2467514",lang:"de",orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){var t=this.options.url;return"function"==typeof t?$.proxy(t,this)():t},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){return $.getJSON(this.options.backendUrl+"?url="+encodeURIComponent(this.getURL()))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,n="orientation-"+this.options.orientation,i=$("<ul>").addClass(r).addClass(n);this.services.forEach(function(e){var r=$('<li class="shariff-button">').addClass(e.name),n='<span class="share_text">'+t.getLocalized(e,"shareText"),o=$("<a>").attr("href",e.shareUrl).append(n);e.popup?o.attr("rel","popup"):o.attr("target","_blank"),o.attr("title",t.getLocalized(e,"title")),r.append(o),i.append(r)}),i.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r=$(this).attr("title"),n="600",i="460",o="width="+n+",height="+i;global.window.open(e,r,o)}),e.append(i)},abbreviateText:function(t,e){var r=decodeURIComponent(t);if(r.length<=e)return t;var n=r.substring(0,e-1).lastIndexOf(" ");return r=encodeURIComponent(r.substring(0,n))+"…"},getShareText:function(){var t=this.getMeta("DC.title"),e=this.getMeta("DC.creator");return t.length>0&&e.length>0?t+=" - "+e:t=$("title").text(),encodeURIComponent(this.abbreviateText(t,120))}},module.exports=_Shariff,$(".shariff").each(function(){this.shariff=new _Shariff(this)});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./services/facebook":2,"./services/googleplus":3,"./services/info":4,"./services/mail":5,"./services/twitter":6,"./services/whatsapp":7,"jquery":1}]},{},[8]);
|
examples/with-url-object-routing/pages/about.js | nelak/next.js | import React from 'react'
import Link from 'next/link'
import Router from 'next/router'
const href = {
pathname: '/about',
query: { name: 'zeit' }
}
const as = {
pathname: '/about/zeit',
hash: 'title-1'
}
const handleClick = () => Router.push(href, as)
export default (props) => (
<div>
<h1>About {props.url.query.name}</h1>
{props.url.query.name === 'zeit' ? (
<Link href='/'>
<a>Go to home page</a>
</Link>
) : (
<button onClick={handleClick}>Go to /about/zeit</button>
)}
</div>
)
|
packages/dom-event-testing-library/touchStore.js | ericyang321/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
/**
* Touch events state machine.
*
* Keeps track of the active pointers and allows them to be reflected in touch events.
*/
const activeTouches = new Map();
export function addTouch(touch) {
const identifier = touch.identifier;
const target = touch.target;
if (!activeTouches.has(target)) {
activeTouches.set(target, new Map());
}
if (activeTouches.get(target).get(identifier)) {
// Do not allow existing touches to be overwritten
console.error(
'Touch with identifier %s already exists. Did not record touch start.',
identifier,
);
} else {
activeTouches.get(target).set(identifier, touch);
}
}
export function updateTouch(touch) {
const identifier = touch.identifier;
const target = touch.target;
if (activeTouches.get(target) != null) {
activeTouches.get(target).set(identifier, touch);
} else {
console.error(
'Touch with identifier %s does not exist. Cannot record touch move without a touch start.',
identifier,
);
}
}
export function removeTouch(touch) {
const identifier = touch.identifier;
const target = touch.target;
if (activeTouches.get(target) != null) {
if (activeTouches.get(target).has(identifier)) {
activeTouches.get(target).delete(identifier);
} else {
console.error(
'Touch with identifier %s does not exist. Cannot record touch end without a touch start.',
identifier,
);
}
}
}
export function getTouches() {
const touches = [];
activeTouches.forEach((_, target) => {
touches.push(...getTargetTouches(target));
});
return touches;
}
export function getTargetTouches(target) {
if (activeTouches.get(target) != null) {
return Array.from(activeTouches.get(target).values());
}
return [];
}
export function clear() {
activeTouches.clear();
}
|
app/javascript/mastodon/components/extended_video_player.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class ExtendedVideoPlayer extends React.PureComponent {
static propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
time: PropTypes.number,
controls: PropTypes.bool.isRequired,
muted: PropTypes.bool.isRequired,
onClick: PropTypes.func,
};
handleLoadedData = () => {
if (this.props.time) {
this.video.currentTime = this.props.time;
}
}
componentDidMount () {
this.video.addEventListener('loadeddata', this.handleLoadedData);
}
componentWillUnmount () {
this.video.removeEventListener('loadeddata', this.handleLoadedData);
}
setRef = (c) => {
this.video = c;
}
handleClick = e => {
e.stopPropagation();
const handler = this.props.onClick;
if (handler) handler();
}
render () {
const { src, muted, controls, alt } = this.props;
return (
<div className='extended-video-player'>
<video
ref={this.setRef}
src={src}
autoPlay
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
muted={muted}
controls={controls}
loop={!controls}
onClick={this.handleClick}
/>
</div>
);
}
}
|
resources/assets/bower_components/rxjs/dist/rx.compat.js | docit/core | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'function': true,
'object': true
};
var
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeSelf = objectTypes[typeof self] && self.Object && self,
freeWindow = objectTypes[typeof window] && window && window.Object && window,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
var root = root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = arr[i]; }
return a;
}
var errorObj = {e: {}};
function tryCatcherGen(tryCatchTarget) {
return function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
}
var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
return tryCatcherGen(fn);
}
function thrower(e) {
throw e;
}
Rx.config.longStackSupport = false;
var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
hasStacks = !!stacks.e && !!stacks.e.stack;
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = 'From previous event:';
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === 'object' &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split('\n'), desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join('\n');
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf('(module.js:') !== -1 ||
stackLine.indexOf('(node.js:') !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split('\n');
var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: 'at functionName (filename:lineNumber:columnNumber)'
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: 'at filename:lineNumber:columnNumber'
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
this.name = 'EmptyError';
Error.call(this);
};
EmptyError.prototype = Object.create(Error.prototype);
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
this.name = 'ObjectDisposedError';
Error.call(this);
};
ObjectDisposedError.prototype = Object.create(Error.prototype);
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
this.name = 'ArgumentOutOfRangeError';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
this.name = 'NotSupportedError';
Error.call(this);
};
NotSupportedError.prototype = Object.create(Error.prototype);
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
this.name = 'NotImplementedError';
Error.call(this);
};
NotImplementedError.prototype = Object.create(Error.prototype);
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
var slice = Array.prototype.slice,
toString = Object.prototype.toString;
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
var boxedString = Object('a'),
splitString = boxedString[0] !== 'a' || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && toString.call(this) === stringClass ?
this.split('') :
object,
length = self.length >>> 0,
thisp = arguments[1];
if (toString.call(fun) !== funcClass) {
throw new TypeError(fun + ' is not a function');
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && toString.call(this) === stringClass ?
this.split('') :
object,
length = self.length >>> 0,
result = new Array(length),
thisp = arguments[1];
if (toString.call(fun) !== funcClass) {
throw new TypeError(fun + ' is not a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return toString.call(arg) === arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Fix for Tessel
if (!Object.prototype.propertyIsEnumerable) {
Object.prototype.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
if (typeof Object.create !== 'function') {
// Production steps of ECMA-262, Edition 5, 15.2.3.5
// Reference: http://es5.github.io/#x15.2.3.5
Object.create = (function() {
function Temp() {}
var hasOwn = Object.prototype.hasOwnProperty;
return function (O) {
if (typeof O !== 'object') {
throw new TypeError('Object prototype may only be an Object or null');
}
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null;
if (arguments.length > 1) {
// Object.defineProperties does ToObject on its first argument.
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
// 5. Return obj
return obj;
};
})();
}
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
// Single assignment
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SingleAssignmentDisposable.prototype.getDisposable = function () {
return this.current;
};
SingleAssignmentDisposable.prototype.setDisposable = function (value) {
if (this.current) { throw new Error('Disposable has already been assigned'); }
var shouldDispose = this.isDisposed;
!shouldDispose && (this.current = value);
shouldDispose && value && value.dispose();
};
SingleAssignmentDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
// Multiple assignment disposable
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
SerialDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
/** Determines whether the given object is a scheduler */
Scheduler.isScheduler = function (s) {
return s instanceof Scheduler;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
action(state, innerAction);
return group;
function innerAction(state2) {
var isAdded = false, isDone = false;
var d = scheduler.scheduleWithState(state2, scheduleWork);
if (!isDone) {
group.add(d);
isAdded = true;
}
function scheduleWork(_, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
action(state3, innerAction);
return disposableEmpty;
}
}
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
action(state, innerAction);
return group;
function innerAction(state2, dueTime1) {
var isAdded = false, isDone = false;
var d = scheduler[method](state2, dueTime1, scheduleWork);
if (!isDone) {
group.add(d);
isAdded = true;
}
function scheduleWork(_, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
action(state3, innerAction);
return disposableEmpty;
}
}
}
function invokeRecDateRelative(s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
}
function invokeRecDateAbsolute(s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, invokeRecDateRelative);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, invokeRecDateAbsolute);
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.shift();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = [si];
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.push(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else if (root.attachEvent) {
root.attachEvent('onmessage', onGlobalPostMessage);
} else {
root.onmessage = onGlobalPostMessage;
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () {
function scheduleNow(state, action) {
var scheduler = this, disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
!disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable();
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var id = localSetTimeout(function () {
!disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
var self = this;
return new AnonymousObserver(
function (x) { self.onNext(x); },
function (err) { self.onError(err); },
function () { self.onCompleted(); });
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
var cb = bindCallback(handler, thisArg, 1);
return new AnonymousObserver(function (x) {
return cb(notificationCreateOnNext(x));
}, function (e) {
return cb(notificationCreateOnError(e));
}, function () {
return cb(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
!this.isStopped && this.next(value);
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this, function (parent, self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
var res = tryCatch(work)();
if (res === errorObj) {
parent.queue = [];
parent.hasFaulted = true;
return thrower(res.e);
}
self(parent);
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function makeSubscribe(self, subscribe) {
return function (o) {
var oldOnError = o.onError;
o.onError = function (e) {
makeStackTraceLong(e, self);
oldOnError.call(o, e);
};
return subscribe.call(self, o);
};
}
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
var e = tryCatch(thrower)(new Error()).e;
this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
this._subscribe = makeSubscribe(this, subscribe);
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Determines whether the given object is an Observable
* @param {Any} An object to determine whether it is an Observable
* @returns {Boolean} true if an Observable, else false.
*/
Observable.isObservable = function (o) {
return o && isFunction(o.subscribe);
}
/**
* Subscribes an o to the observable sequence.
* @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
return this._subscribe(typeof oOrOnNext === 'object' ?
oOrOnNext :
observerCreate(oOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
var FlatMapObservable = (function(__super__){
inherits(FlatMapObservable, __super__);
function FlatMapObservable(source, selector, resultSelector, thisArg) {
this.resultSelector = Rx.helpers.isFunction(resultSelector) ?
resultSelector : null;
this.selector = Rx.internals.bindCallback(Rx.helpers.isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
this.source = source;
__super__.call(this);
}
FlatMapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
};
function InnerObserver(observer, selector, resultSelector, source) {
this.i = 0;
this.selector = selector;
this.resultSelector = resultSelector;
this.source = source;
this.isStopped = false;
this.o = observer;
}
InnerObserver.prototype._wrapResult = function(result, x, i) {
return this.resultSelector ?
result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
result;
};
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) return;
var i = this.i++;
var result = tryCatch(this.selector)(x, i, this.source);
if (result === errorObj) {
return this.o.onError(result.e);
}
Rx.helpers.isPromise(result) && (result = Rx.Observable.fromPromise(result));
(Rx.helpers.isArrayLike(result) || Rx.helpers.isIterable(result)) && (result = Rx.Observable.from(result));
this.o.onNext(this._wrapResult(result, x, i));
};
InnerObserver.prototype.onError = function(e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) {this.isStopped = true; this.o.onCompleted(); }
};
return FlatMapObservable;
}(ObservableBase));
var Enumerable = Rx.internals.Enumerable = function () { };
var ConcatEnumerableObservable = (function(__super__) {
inherits(ConcatEnumerableObservable, __super__);
function ConcatEnumerableObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
function InnerObserver(o, s, e) {
this.o = o;
this.s = s;
this.e = e;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } };
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.s(this.e);
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; };
InnerObserver.prototype.fail = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
return true;
}
return false;
};
return ConcatEnumerableObservable;
}(ObservableBase));
Enumerable.prototype.concat = function () {
return new ConcatEnumerableObservable(this);
};
var CatchErrorObservable = (function(__super__) {
inherits(CatchErrorObservable, __super__);
function CatchErrorObservable(sources) {
this.sources = sources;
__super__.call(this);
}
CatchErrorObservable.prototype.subscribeCore = function (o) {
var e = this.sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return lastException !== null ? o.onError(lastException) : o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return CatchErrorObservable;
}(ObservableBase));
Enumerable.prototype.catchError = function () {
return new CatchErrorObservable(this);
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var RepeatEnumerable = (function (__super__) {
inherits(RepeatEnumerable, __super__);
function RepeatEnumerable(v, c) {
this.v = v;
this.c = c == null ? -1 : c;
}
RepeatEnumerable.prototype[$iterator$] = function () {
return new RepeatEnumerator(this);
};
function RepeatEnumerator(p) {
this.v = p.v;
this.l = p.c;
}
RepeatEnumerator.prototype.next = function () {
if (this.l === 0) { return doneEnumerator; }
if (this.l > 0) { this.l--; }
return { done: false, value: this.v };
};
return RepeatEnumerable;
}(Enumerable));
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
return new RepeatEnumerable(value, repeatCount);
};
var OfEnumerable = (function(__super__) {
inherits(OfEnumerable, __super__);
function OfEnumerable(s, fn, thisArg) {
this.s = s;
this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
}
OfEnumerable.prototype[$iterator$] = function () {
return new OfEnumerator(this);
};
function OfEnumerator(p) {
this.i = -1;
this.s = p.s;
this.l = this.s.length;
this.fn = p.fn;
}
OfEnumerator.prototype.next = function () {
return ++this.i < this.l ?
{ done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
doneEnumerator;
};
return OfEnumerable;
}(Enumerable));
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
return new OfEnumerable(source, selector, thisArg);
};
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
var FromPromiseObservable = (function(__super__) {
inherits(FromPromiseObservable, __super__);
function FromPromiseObservable(p) {
this.p = p;
__super__.call(this);
}
FromPromiseObservable.prototype.subscribeCore = function(o) {
this.p.then(function (data) {
o.onNext(data);
o.onCompleted();
}, function (err) { o.onError(err); });
return disposableEmpty;
};
return FromPromiseObservable;
}(ObservableBase));
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new FromPromiseObservable(promise);
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.a = [];
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.o.onNext(this.a);
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return ToArrayObservable;
}(ObservableBase));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
var EmptyObservable = (function(__super__) {
inherits(EmptyObservable, __super__);
function EmptyObservable(scheduler) {
this.scheduler = scheduler;
__super__.call(this);
}
EmptyObservable.prototype.subscribeCore = function (observer) {
var sink = new EmptySink(observer, this.scheduler);
return sink.run();
};
function EmptySink(observer, scheduler) {
this.observer = observer;
this.scheduler = scheduler;
}
function scheduleItem(s, state) {
state.onCompleted();
return disposableEmpty;
}
EmptySink.prototype.run = function () {
return this.scheduler.scheduleWithState(this.observer, scheduleItem);
};
return EmptyObservable;
}(ObservableBase));
var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (o) {
var sink = new FromSink(o, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(o, parent) {
this.o = o;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
o = this.o,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
var next = tryCatch(it.next).call(it);
if (next === errorObj) { return o.onError(next.e); }
if (next.done) { return o.onCompleted(); }
var result = next.value;
if (isFunction(mapper)) {
result = tryCatch(mapper)(result, i);
if (result === errorObj) { return o.onError(result.e); }
}
o.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(s) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(s) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
var NeverObservable = (function(__super__) {
inherits(NeverObservable, __super__);
function NeverObservable() {
__super__.call(this);
}
NeverObservable.prototype.subscribeCore = function (observer) {
return disposableEmpty;
};
return NeverObservable;
}(ObservableBase));
var NEVER_OBSERVABLE = new NeverObservable();
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return NEVER_OBSERVABLE;
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
var PairsObservable = (function(__super__) {
inherits(PairsObservable, __super__);
function PairsObservable(obj, scheduler) {
this.obj = obj;
this.keys = Object.keys(obj);
this.scheduler = scheduler;
__super__.call(this);
}
PairsObservable.prototype.subscribeCore = function (observer) {
var sink = new PairsSink(observer, this);
return sink.run();
};
return PairsObservable;
}(ObservableBase));
function PairsSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
PairsSink.prototype.run = function () {
var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length;
function loopRecursive(i, recurse) {
if (i < len) {
var key = keys[i];
observer.onNext([key, obj[key]]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new PairsObservable(obj, scheduler);
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.rangeCount = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RepeatObservable(value, repeatCount, scheduler);
};
var JustObservable = (function(__super__) {
inherits(JustObservable, __super__);
function JustObservable(value, scheduler) {
this.value = value;
this.scheduler = scheduler;
__super__.call(this);
}
JustObservable.prototype.subscribeCore = function (observer) {
var sink = new JustSink(observer, this.value, this.scheduler);
return sink.run();
};
function JustSink(observer, value, scheduler) {
this.observer = observer;
this.value = value;
this.scheduler = scheduler;
}
function scheduleItem(s, state) {
var value = state[0], observer = state[1];
observer.onNext(value);
observer.onCompleted();
return disposableEmpty;
}
JustSink.prototype.run = function () {
var state = [this.value, this.observer];
return this.scheduler === immediateScheduler ?
scheduleItem(null, state) :
this.scheduler.scheduleWithState(state, scheduleItem);
};
return JustObservable;
}(ObservableBase));
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new JustObservable(value, scheduler);
};
var ThrowObservable = (function(__super__) {
inherits(ThrowObservable, __super__);
function ThrowObservable(error, scheduler) {
this.error = error;
this.scheduler = scheduler;
__super__.call(this);
}
ThrowObservable.prototype.subscribeCore = function (o) {
var sink = new ThrowSink(o, this);
return sink.run();
};
function ThrowSink(o, p) {
this.o = o;
this.p = p;
}
function scheduleItem(s, state) {
var e = state[0], o = state[1];
o.onError(e);
}
ThrowSink.prototype.run = function () {
return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem);
};
return ThrowObservable;
}(ObservableBase));
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new ThrowObservable(error, scheduler);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (o) {
var disposable = disposableEmpty;
var resource = tryCatch(resourceFactory)();
if (resource === errorObj) {
return new CompositeDisposable(observableThrow(resource.e).subscribe(o), disposable);
}
resource && (disposable = resource);
var source = tryCatch(observableFactory)(resource);
if (source === errorObj) {
return new CompositeDisposable(observableThrow(source.e).subscribe(o), disposable);
}
return new CompositeDisposable(source.subscribe(o), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
var leftSubscribe = observerCreate(
function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
},
function (e) {
choiceL();
choice === leftChoice && observer.onError(e);
},
function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}
);
var rightSubscribe = observerCreate(
function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
},
function (e) {
choiceR();
choice === rightChoice && observer.onError(e);
},
function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}
);
leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
function amb(p, c) { return p.amb(c); }
/**
* Propagates the observable sequence or Promise that reacts first.
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items;
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
var len = arguments.length;
items = new Array(items);
for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
}
for (var i = 0, len = items.length; i < len; i++) {
acc = amb(acc, items[i]);
}
return acc;
};
var CatchObserver = (function(__super__) {
inherits(CatchObserver, __super__);
function CatchObserver(o, s, fn) {
this._o = o;
this._s = s;
this._fn = fn;
__super__.call(this);
}
CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
CatchObserver.prototype.error = function (e) {
var result = tryCatch(this._fn)(e);
if (result === errorObj) { return this._o.onError(result.e); }
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
this._s.setDisposable(d);
d.setDisposable(result.subscribe(this._o));
};
return CatchObserver;
}(AbstractObserver));
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(new CatchObserver(o, subscription, handler)));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = function (handlerOrSecond) {
return isFunction(handlerOrSecond) ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable['catch'] = function () {
var items;
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
var len = arguments.length;
items = new Array(len);
for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
function falseFactory() { return false; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
var ConcatObservable = (function(__super__) {
inherits(ConcatObservable, __super__);
function ConcatObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatObservable.prototype.subscribeCore = function(o) {
var sink = new ConcatSink(this.sources, o);
return sink.run();
};
function ConcatSink(sources, o) {
this.sources = sources;
this.o = o;
}
ConcatSink.prototype.run = function () {
var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o;
var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) {
if (isDisposed) { return; }
if (i === length) {
return o.onCompleted();
}
// Check if promise
var currentValue = sources[i];
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function (x) { o.onNext(x); },
function (e) { o.onError(e); },
function () { self(i + 1); }
));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return ConcatObservable;
}(ObservableBase));
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return new ConcatObservable(args);
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObservable;
}(ObservableBase));
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
var SwitchObservable = (function(__super__) {
inherits(SwitchObservable, __super__);
function SwitchObservable(source) {
this.source = source;
__super__.call(this);
}
SwitchObservable.prototype.subscribeCore = function (o) {
var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
return new CompositeDisposable(s, inner);
};
function SwitchObserver(o, inner) {
this.o = o;
this.inner = inner;
this.stopped = false;
this.latest = 0;
this.hasLatest = false;
this.isStopped = false;
}
SwitchObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
var d = new SingleAssignmentDisposable(), id = ++this.latest;
this.hasLatest = true;
this.inner.setDisposable(d);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
};
SwitchObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
SwitchObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.stopped = true;
!this.hasLatest && this.o.onCompleted();
}
};
SwitchObserver.prototype.dispose = function () { this.isStopped = true; };
SwitchObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, id) {
this.parent = parent;
this.id = id;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.parent.latest === this.id && this.parent.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.latest === this.id && this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
if (this.parent.latest === this.id) {
this.parent.hasLatest = false;
this.parent.isStopped && this.parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return SwitchObservable;
}(ObservableBase));
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
return new SwitchObservable(this);
};
var TakeUntilObservable = (function(__super__) {
inherits(TakeUntilObservable, __super__);
function TakeUntilObservable(source, other) {
this.source = source;
this.other = isPromise(other) ? observableFromPromise(other) : other;
__super__.call(this);
}
TakeUntilObservable.prototype.subscribeCore = function(o) {
return new CompositeDisposable(
this.source.subscribe(o),
this.other.subscribe(new InnerObserver(o))
);
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.o.onCompleted();
};
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
!this.isStopped && (this.isStopped = true);
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TakeUntilObservable;
}(ObservableBase));
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
return new TakeUntilObservable(this, other);
};
function falseFactory() { return false; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (observer) {
var n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, function (e) { observer.onError(e); }, noop));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var allValues = [x].concat(values);
if (!hasValueAll) { return; }
var res = tryCatch(resultSelector).apply(null, allValues);
if (res === errorObj) { return observer.onError(res.e); }
observer.onNext(res);
}, function (e) { observer.onError(e); }, function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (arguments.length === 0) { throw new Error('invalid arguments'); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
var parent = this;
args.unshift(parent);
return new AnonymousObservable(function (o) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var queuedValues = queues.map(function (x) { return x.shift(); }),
res = tryCatch(resultSelector).apply(parent, queuedValues);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
}
var first = args.shift();
return first.zip.apply(first, args);
};
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zipIterable = function () {
if (arguments.length === 0) { throw new Error('invalid arguments'); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
var parent = this;
args.unshift(parent);
return new AnonymousObservable(function (o) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
(isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var queuedValues = queues.map(function (x) { return x.shift(); }),
res = tryCatch(resultSelector).apply(parent, queuedValues);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
function asObservable(source) {
return function subscribe(o) { return source.subscribe(o); };
}
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(asObservable(this), this);
};
function toArray(x) { return x.toArray(); }
function notEmpty(x) { return x.length > 0; }
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
typeof skip !== 'number' && (skip = count);
return this.windowWithCount(count, skip)
.flatMap(toArray)
.filter(notEmpty);
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var DistinctUntilChangedObservable = (function(__super__) {
inherits(DistinctUntilChangedObservable, __super__);
function DistinctUntilChangedObservable(source, keyFn, comparer) {
this.source = source;
this.keyFn = keyFn;
this.comparer = comparer;
__super__.call(this);
}
DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
};
return DistinctUntilChangedObservable;
}(ObservableBase));
var DistinctUntilChangedObserver = (function(__super__) {
inherits(DistinctUntilChangedObserver, __super__);
function DistinctUntilChangedObserver(o, keyFn, comparer) {
this.o = o;
this.keyFn = keyFn;
this.comparer = comparer;
this.hasCurrentKey = false;
this.currentKey = null;
__super__.call(this);
}
DistinctUntilChangedObserver.prototype.next = function (x) {
var key = x, comparerEquals;
if (isFunction(this.keyFn)) {
key = tryCatch(this.keyFn)(x);
if (key === errorObj) { return this.o.onError(key.e); }
}
if (this.hasCurrentKey) {
comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
}
if (!this.hasCurrentKey || !comparerEquals) {
this.hasCurrentKey = true;
this.currentKey = key;
this.o.onNext(x);
}
};
DistinctUntilChangedObserver.prototype.error = function(e) {
this.o.onError(e);
};
DistinctUntilChangedObserver.prototype.completed = function () {
this.o.onCompleted();
};
return DistinctUntilChangedObserver;
}(AbstractObserver));
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
* @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keyFn, comparer) {
comparer || (comparer = defaultComparer);
return new DistinctUntilChangedObservable(this, keyFn, comparer);
};
var TapObservable = (function(__super__) {
inherits(TapObservable,__super__);
function TapObservable(source, observerOrOnNext, onError, onCompleted) {
this.source = source;
this._oN = observerOrOnNext;
this._oE = onError;
this._oC = onCompleted;
__super__.call(this);
}
TapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this));
};
function InnerObserver(o, p) {
this.o = o;
this.t = !p._oN || isFunction(p._oN) ?
observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
p._oN;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var res = tryCatch(this.t.onNext).call(this.t, x);
if (res === errorObj) { this.o.onError(res.e); }
this.o.onNext(x);
};
InnerObserver.prototype.onError = function(err) {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onError).call(this.t, err);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onCompleted).call(this.t);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TapObservable;
}(ObservableBase));
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
return new TapObservable(this, observerOrOnNext, onError, onCompleted);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = tryCatch(source.subscribe).call(source, observer);
if (subscription === errorObj) {
action();
return thrower(subscription.e);
}
return disposableCreate(function () {
var r = tryCatch(subscription.dispose).call(subscription);
action();
r === errorObj && thrower(r.e);
});
}, this);
};
var IgnoreElementsObservable = (function(__super__) {
inherits(IgnoreElementsObservable, __super__);
function IgnoreElementsObservable(source) {
this.source = source;
__super__.call(this);
}
IgnoreElementsObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = noop;
InnerObserver.prototype.onError = function (err) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
return IgnoreElementsObservable;
}(ObservableBase));
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
return new IgnoreElementsObservable(this);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
var ScanObservable = (function(__super__) {
inherits(ScanObservable, __super__);
function ScanObservable(source, accumulator, hasSeed, seed) {
this.source = source;
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ScanObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o,this));
};
return ScanObservable;
}(ObservableBase));
function InnerObserver(o, parent) {
this.o = o;
this.accumulator = parent.accumulator;
this.hasSeed = parent.hasSeed;
this.seed = parent.seed;
this.hasAccumulation = false;
this.accumulation = null;
this.hasValue = false;
this.isStopped = false;
}
InnerObserver.prototype = {
onNext: function (x) {
if (this.isStopped) { return; }
!this.hasValue && (this.hasValue = true);
if (this.hasAccumulation) {
this.accumulation = tryCatch(this.accumulator)(this.accumulation, x);
} else {
this.accumulation = this.hasSeed ? tryCatch(this.accumulator)(this.seed, x) : x;
this.hasAccumulation = true;
}
if (this.accumulation === errorObj) { return this.o.onError(this.accumulation.e); }
this.o.onNext(this.accumulation);
},
onError: function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
},
onCompleted: function () {
if (!this.isStopped) {
this.isStopped = true;
!this.hasValue && this.hasSeed && this.o.onNext(this.seed);
this.o.onCompleted();
}
},
dispose: function() { this.isStopped = true; },
fail: function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
}
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator = arguments[0];
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new ScanObservable(this, accumulator, hasSeed, seed);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1);
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
function innerMap(selector, self) {
return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
return new MapObservable(this.source, innerMap(selector, this), thisArg);
};
MapObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this));
};
function InnerObserver(o, selector, source) {
this.o = o;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector)(x, this.i++, this.source);
if (result === errorObj) { return this.o.onError(result.e); }
this.o.onNext(result);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return MapObservable;
}(ObservableBase));
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
function plucker(args, len) {
return function mapper(x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
}
}
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var len = arguments.length, args = new Array(len);
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return this.map(plucker(args, len));
};
observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
};
//
//Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit, selector, resultSelector, thisArg) {
// return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit);
//};
//
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
};
var SkipObservable = (function(__super__) {
inherits(SkipObservable, __super__);
function SkipObservable(source, count) {
this.source = source;
this.skipCount = count;
__super__.call(this);
}
SkipObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.skipCount));
};
function InnerObserver(o, c) {
this.c = c;
this.r = c;
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
if (this.r <= 0) {
this.o.onNext(x);
} else {
this.r--;
}
};
InnerObserver.prototype.onError = function(e) {
if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function(e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return SkipObservable;
}(ObservableBase));
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
return new SkipObservable(this, count);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining <= 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.predicate, this));
};
function innerPredicate(predicate, self) {
return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
}
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
};
function InnerObserver(o, predicate, source) {
this.o = o;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.o.onError(shouldYield.e);
}
shouldYield && this.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return FilterObservable;
}(ObservableBase));
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
var res = tryCatch(xform['@@transducer/step']).call(xform, o, v);
if (res === errorObj) { o.onError(res.e); }
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.__subscribe).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function innerSubscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
this.__subscribe = subscribe;
__super__.call(this, innerSubscribe);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
src/components/container/ProductPage/ProductPage.js | AurimasSk/DemoStore | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as productActions from "../../../actions/productActions";
import ProductDetails from '../../presentational/ProductDetails/ProductDetails';
class ProductPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
product: Object.assign({}, props.product),
};
}
componentWillReceiveProps(nextProps) {
if (this.props.product.id != nextProps.product.id) {
// Necessary to populate from when existing product is loaded directly
this.setState({ product: Object.assign({}, nextProps.product) });
}
}
render() {
return (
<div>
{
<ProductDetails product={this.props.product}/>
}
</div>
);
}
}
function getProductById(products, id) {
const product = products.filter(product => product.id == id);
if (product)
return product[0];
return null;
}
// ownProps represents any props passed to our component
function mapStateToProps(state, ownProps) {
const productId = ownProps.params.id;
let product = { id: '', info: '', otherDetails: '' };
if (productId && state.products.length > 0) {
product = getProductById(state.products, productId);
}
return {
product: product,
};
}
function mapDispatchToProps(dispatch) {
return {
productActions: bindActionCreators(productActions, dispatch)
};
}
ProductPage.propTypes = {
product: PropTypes.object.isRequired,
productActions: PropTypes.object.isRequired
};
export default connect(mapStateToProps, mapDispatchToProps)(ProductPage);
|
app/containers/HomePage/content.js | ledminh/css-pages | import styled from 'styled-components';
import React from 'react';
const Style = styled.div`
width: 70%;
min-width: 400px;
margin: auto;
margin-top: 25px;
border: 2px solid black;
border-radius: 10px;
padding: 10px;
`;
const Content = styled.div`
border: 1px solid black;
padding: 10px;
width: 100%;
`;
const Tag = styled.div`
border: 1px solid black;
background-color: ${props => props.odd? 'white' : '#dedfe0'};
border-radius: 10px;
padding: 5px 0px 5px 15px;
font-weight: bold;
margin-bottom: 10px;
cursor: pointer;
&:hover {
background-color: #83b3e2;
}
`;
export default ({data}) => (
<Style>
<Content>
{
data.map((elem, i) => <Tag key={i} odd={i%2 === 1} onClick={() => open(elem.link)}>{elem.name}</Tag>)
}
</Content>
</Style>
);;
|
src/js/components/icons/base/Plan.js | odedre/grommet-final | /**
* @description Plan SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M18,4 L18,0 L18,4 Z M7,18 L5,18 L7,18 Z M19,18 L9,18 L19,18 Z M7,14 L5,14 L7,14 Z M19,14 L9,14 L19,14 Z M6,4 L6,0 L6,4 Z M1,9 L23,9 L1,9 Z M1,23 L23,23 L23,4 L1,4 L1,23 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-plan`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'plan');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M18,4 L18,0 L18,4 Z M7,18 L5,18 L7,18 Z M19,18 L9,18 L19,18 Z M7,14 L5,14 L7,14 Z M19,14 L9,14 L19,14 Z M6,4 L6,0 L6,4 Z M1,9 L23,9 L1,9 Z M1,23 L23,23 L23,4 L1,4 L1,23 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Plan';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
__tests__/index.android.js | HossamSamir/instagramClone | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
pootle/static/js/browser/components/NumberPill.js | iafan/zing | /*
* Copyright (C) Zing contributors.
*
* This file is a part of the Zing project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import { toLocaleString } from 'utils/i18n';
const NumberPill = React.createClass({
propTypes: {
n: React.PropTypes.number,
url: React.PropTypes.string.isRequired,
},
render() {
if (!this.props.n) {
return <span className="zero">0</span>;
}
return (
<a
className="stats-data"
href={this.props.url}
>
{toLocaleString(this.props.n)}
</a>
);
},
});
export default NumberPill;
|
src/index.js | filtudo/eebook | import './index.css'
import React from 'react'
import {render} from 'react-dom'
import App from './App'
render(<App/>, document.querySelector('#app'))
|
packages/material-ui-icons/src/Receipt.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M18 17H6v-2h12v2zm0-4H6v-2h12v2zm0-4H6V7h12v2zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'Receipt');
|
app/javascript/flavours/glitch/features/compose/components/character_counter.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
export default class CharacterCounter extends React.PureComponent {
static propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
};
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
|
app/javascript/mastodon/features/community_timeline/components/column_settings.js | d6rkaiz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage } from 'react-intl';
import SettingToggle from '../../notifications/components/setting_toggle';
export default @injectIntl
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
};
render () {
const { settings, onChange } = this.props;
return (
<div>
<div className='column-settings__row'>
<SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} />
</div>
</div>
);
}
}
|
docs/src/app/components/Carbon.js | manchesergit/material-ui | import React from 'react';
require('./Carbon.css');
class Carbon extends React.Component {
componentDidMount() {
if (process.env.NODE_ENV !== 'production') {
return;
}
const script = document.createElement('script');
script.setAttribute('async', '');
script.src =
'//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=materialuicom';
script.id = '_carbonads_js';
const ad = document.querySelector('#ad');
if (ad) {
ad.appendChild(script);
}
}
render() {
return <div id="ad" />;
}
}
export default Carbon;
|
src/main/webapp/resources/modules/table/MyCards.js | cwoolner/flex-poker | import React from 'react'
import CardData from './CardData'
export default ({myLeftCardId, myRightCardId}) => {
return (
<div>
<img className={"my-cards"} src={CardData[myLeftCardId]} />
<img className={"my-cards"} src={CardData[myRightCardId]} />
</div>
)
}
|
public/js/cat_source/es6/components/outsource/OpenJobBox.js | matecat/MateCat | import React from 'react'
class OpenJobBox extends React.Component {
constructor(props) {
super(props)
}
openJob() {
return this.props.url
}
getUrl() {
return (
window.location.protocol + '//' + window.location.host + this.props.url
)
}
render() {
return (
<div className="open-job-box">
<div className="title">Open job:</div>
<div className="title-url">
<a className="job-url" href={this.openJob()} target="_blank">
{this.getUrl()}
</a>
<a
className="ui primary button"
href={this.openJob()}
target="_blank"
>
Open job
</a>
</div>
</div>
)
}
}
export default OpenJobBox
|
src/components/PluginContainer.js | metasfresh/metasfresh-webui-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import Container from '../components/Container';
const pluginWrapper = function pluginWrapper(WrappedComponent, ChildComponent) {
return class WrappedPlugin extends Component {
render() {
return <WrappedComponent component={ChildComponent} {...this.props} />;
}
};
};
class PluginContainer extends Component {
renderChildren() {
const { pluginModal, component, dispatch } = this.props;
const { store } = this.context;
const redirectPush = bindActionCreators(push, dispatch);
const TagName = component;
const renderedTag = (
<TagName
{...this.props}
redirectPush={redirectPush}
dispatch={dispatch}
store={store}
/>
);
if (!pluginModal) {
return <div className="plugin-container">{TagName && renderedTag}</div>;
}
return renderedTag;
}
render() {
const { modal, rawModal, pluginModal, breadcrumb } = this.props;
return (
<Container {...{ modal, rawModal, pluginModal }} breadcrumb={breadcrumb}>
{this.renderChildren()}
</Container>
);
}
}
PluginContainer.propTypes = {
store: PropTypes.object,
pluginModal: PropTypes.any,
dispatch: PropTypes.func,
modal: PropTypes.any,
rawModal: PropTypes.any,
breadcrumb: PropTypes.any,
component: PropTypes.node,
};
function mapStateToProps(state) {
const { windowHandler, menuHandler } = state;
const { modal, rawModal, pluginModal } = windowHandler || {
modal: {},
rawModal: {},
pluginModal: {},
};
return {
modal,
rawModal,
pluginModal,
breadcrumb: menuHandler.breadcrumb,
};
}
export default connect(mapStateToProps)(PluginContainer);
export { pluginWrapper };
|
tech_stack/index.ios.js | DaveWJ/LearningReact | /**
* 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 tech_stack 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.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake 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('tech_stack', () => tech_stack);
|
packages/reactor-kitchensink/src/examples/FormFields/ToggleField/ToggleField.js | dbuhrman/extjs-reactor | import React from 'react';
import { FormPanel, ToggleField } from '@extjs/ext-react';
export default function ToggleFieldExample() {
return (
<FormPanel shadow defaults={{ padding: '0 10'}} padding="20">
<ToggleField boxLabel="On" value={true}/>
<ToggleField boxLabel="Off" value={false}/>
<ToggleField boxLabel="Disabled" disabled />
<ToggleField boxLabel="Disabled (On)" disabled value={true} />
</FormPanel>
)
} |
test/fixtures-es6-react-project/public/app.js | herdemir/systemjs-hot-reloader | import React from 'react'
import ReactDOM from 'react-dom/server'
import injectTapEventPlugin from 'react-tap-event-plugin'
import Home from './routes/home'
// Needed for onTouchTap
// Can go away when react 1.0 release
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin()
let output = ReactDOM.renderToString((
<Home/>
))
console.log(output)
|
Examples/UIExplorer/AlertIOSExample.js | daveenguyen/react-native | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
StyleSheet,
View,
Text,
TouchableHighlight,
AlertIOS,
} = React;
exports.framework = 'React';
exports.title = 'AlertIOS';
exports.description = 'iOS alerts and action sheets';
exports.examples = [{
title: 'Alerts',
render() {
return (
<View>
<TouchableHighlight style={styles.wrapper}
onPress={() => AlertIOS.alert(
'Foo Title',
'My Alert Msg'
)}>
<View style={styles.button}>
<Text>Alert with message and default button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => AlertIOS.alert(
null,
null,
[
{text: 'Button', onPress: () => console.log('Button Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with only one button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => AlertIOS.alert(
'Foo Title',
'My Alert Msg',
[
{text: 'Foo', onPress: () => console.log('Foo Pressed!')},
{text: 'Bar', onPress: () => console.log('Bar Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with two buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => AlertIOS.alert(
'Foo Title',
null,
[
{text: 'Foo', onPress: () => console.log('Foo Pressed!')},
{text: 'Bar', onPress: () => console.log('Bar Pressed!')},
{text: 'Baz', onPress: () => console.log('Baz Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with 3 buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => AlertIOS.alert(
'Foo Title',
'My Alert Msg',
'..............'.split('').map((dot, index) => ({
text: 'Button ' + index,
onPress: () => console.log('Pressed ' + index)
}))
)}>
<View style={styles.button}>
<Text>Alert with too many buttons</Text>
</View>
</TouchableHighlight>
</View>
);
}
},
{
title: 'Prompt',
render(): React.Component {
return <PromptExample />
}
}];
class PromptExample extends React.Component {
constructor(props) {
super(props);
this.promptResponse = this.promptResponse.bind(this);
this.state = {
promptValue: undefined,
};
this.title = 'Type a value';
this.defaultValue = 'Default value';
this.buttons = [{
text: 'Custom cancel',
}, {
text: 'Custom OK',
onPress: this.promptResponse
}];
}
render() {
return (
<View>
<Text style={{marginBottom: 10}}>
<Text style={{fontWeight: 'bold'}}>Prompt value:</Text> {this.state.promptValue}
</Text>
<TouchableHighlight
style={styles.wrapper}
onPress={this.prompt.bind(this, this.title, this.promptResponse)}>
<View style={styles.button}>
<Text>
prompt with title & callback
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={this.prompt.bind(this, this.title, this.buttons)}>
<View style={styles.button}>
<Text>
prompt with title & custom buttons
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={this.prompt.bind(this, this.title, this.defaultValue, this.promptResponse)}>
<View style={styles.button}>
<Text>
prompt with title, default value & callback
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={this.prompt.bind(this, this.title, this.defaultValue, this.buttons)}>
<View style={styles.button}>
<Text>
prompt with title, default value & custom buttons
</Text>
</View>
</TouchableHighlight>
</View>
);
}
prompt() {
// Flow's apply support is broken: #7035621
((AlertIOS.prompt: any).apply: any)(AlertIOS, arguments);
}
promptResponse(promptValue) {
this.setState({ promptValue });
}
}
var styles = StyleSheet.create({
wrapper: {
borderRadius: 5,
marginBottom: 5,
},
button: {
backgroundColor: '#eeeeee',
padding: 10,
},
});
|
client/acp/src/view/display/section-loading.js | NicolasSiver/nodebb-plugin-ns-awards | import React from 'react';
export default class SectionLoading extends React.Component {
render() {
return (
<div className="section-loading">
<div className="section-loading__animation">
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="none" strokeWidth="6" strokeLinecap="round">
<animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502"></animate>
<animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4"></animate>
</circle>
</svg>
</div>
</div>
);
}
}
|
ajax/libs/onsen/2.0.0-alpha.14/js/onsenui.min.js | hanbyul-here/cdnjs | /*! onsenui v2.0.0-alpha.14 - 2015-11-10 */
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}!function(){function getAttributes(element){return Node_get_attributes.call(element)}function setAttribute(element,attribute,value){try{Element_setAttribute.call(element,attribute,value)}catch(e){}}function removeAttribute(element,attribute){Element_removeAttribute.call(element,attribute)}function childNodes(element){return Node_get_childNodes.call(element)}function empty(element){for(;element.childNodes.length;)element.removeChild(element.lastChild)}function insertAdjacentHTML(element,position,html){HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element,position,html)}function inUnsafeMode(){var isUnsafe=!0;try{detectionDiv.innerHTML="<test/>"}catch(ex){isUnsafe=!1}return isUnsafe}function cleanse(html,targetElement){function cleanseAttributes(element){var attributes=getAttributes(element);if(attributes&&attributes.length){for(var events,i=0,len=attributes.length;len>i;i++){var attribute=attributes[i],name=attribute.name;"o"!==name[0]&&"O"!==name[0]||"n"!==name[1]&&"N"!==name[1]||(events=events||[],events.push({name:attribute.name,value:attribute.value}))}if(events)for(var i=0,len=events.length;len>i;i++){var attribute=events[i];removeAttribute(element,attribute.name),setAttribute(element,"x-"+attribute.name,attribute.value)}}for(var children=childNodes(element),i=0,len=children.length;len>i;i++)cleanseAttributes(children[i])}var cleaner=document.implementation.createHTMLDocument("cleaner");empty(cleaner.documentElement),MSApp.execUnsafeLocalFunction(function(){insertAdjacentHTML(cleaner.documentElement,"afterbegin",html)});var scripts=cleaner.documentElement.querySelectorAll("script");Array.prototype.forEach.call(scripts,function(script){switch(script.type.toLowerCase()){case"":script.type="text/inert";break;case"text/javascript":case"text/ecmascript":case"text/x-javascript":case"text/jscript":case"text/livescript":case"text/javascript1.1":case"text/javascript1.2":case"text/javascript1.3":script.type="text/inert-"+script.type.slice("text/".length);break;case"application/javascript":case"application/ecmascript":case"application/x-javascript":script.type="application/inert-"+script.type.slice("application/".length)}}),cleanseAttributes(cleaner.documentElement);var cleanedNodes=[];return"HTML"===targetElement.tagName?cleanedNodes=Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes):(cleaner.head&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes))),cleaner.body&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)))),cleanedNodes}function cleansePropertySetter(property,setter){var propertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,property),originalSetter=propertyDescriptor.set;Object.defineProperty(HTMLElement.prototype,property,{get:propertyDescriptor.get,set:function(value){if(window.WinJS&&window.WinJS._execUnsafe&&inUnsafeMode())originalSetter.call(this,value);else{var that=this,nodes=cleanse(value,that);MSApp.execUnsafeLocalFunction(function(){setter(propertyDescriptor,that,nodes)})}},enumerable:propertyDescriptor.enumerable,configurable:propertyDescriptor.configurable})}if(window.MSApp&&MSApp.execUnsafeLocalFunction){var Element_setAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"setAttribute").value,Element_removeAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"removeAttribute").value,HTMLElement_insertAdjacentHTMLPropertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"insertAdjacentHTML"),Node_get_attributes=Object.getOwnPropertyDescriptor(Node.prototype,"attributes").get,Node_get_childNodes=Object.getOwnPropertyDescriptor(Node.prototype,"childNodes").get,detectionDiv=document.createElement("div");cleansePropertySetter("innerHTML",function(propertyDescriptor,target,elements){empty(target);for(var i=0,len=elements.length;len>i;i++)target.appendChild(elements[i])}),cleansePropertySetter("outerHTML",function(propertyDescriptor,target,elements){for(var i=0,len=elements.length;len>i;i++)target.insertAdjacentElement("afterend",elements[i]);target.parentNode.removeChild(target)})}}(),document.registerElement=void 0,"undefined"==typeof WeakMap&&!function(){var defineProperty=Object.defineProperty,counter=Date.now()%1e9,WeakMap=function(){this.name="__st"+(1e9*Math.random()>>>0)+(counter++ +"__")};WeakMap.prototype={set:function(key,value){var entry=key[this.name];return entry&&entry[0]===key?entry[1]=value:defineProperty(key,this.name,{value:[key,value],writable:!0}),this},get:function(key){var entry;return(entry=key[this.name])&&entry[0]===key?entry[1]:void 0},"delete":function(key){var entry=key[this.name];return entry&&entry[0]===key?(entry[0]=entry[1]=void 0,
!0):!1},has:function(key){var entry=key[this.name];return entry?entry[0]===key:!1}},window.WeakMap=WeakMap}(),function(global){function scheduleCallback(observer){scheduledObservers.push(observer),isScheduled||(isScheduled=!0,setImmediate(dispatchCallbacks))}function wrapIfNeeded(node){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(node)||node}function dispatchCallbacks(){isScheduled=!1;var observers=scheduledObservers;scheduledObservers=[],observers.sort(function(o1,o2){return o1.uid_-o2.uid_});var anyNonEmpty=!1;observers.forEach(function(observer){var queue=observer.takeRecords();removeTransientObserversFor(observer),queue.length&&(observer.callback_(queue,observer),anyNonEmpty=!0)}),anyNonEmpty&&dispatchCallbacks()}function removeTransientObserversFor(observer){observer.nodes_.forEach(function(node){var registrations=registrationsTable.get(node);registrations&®istrations.forEach(function(registration){registration.observer===observer&®istration.removeTransientObservers()})})}function forEachAncestorAndObserverEnqueueRecord(target,callback){for(var node=target;node;node=node.parentNode){var registrations=registrationsTable.get(node);if(registrations)for(var j=0;j<registrations.length;j++){var registration=registrations[j],options=registration.options;if(node===target||options.subtree){var record=callback(options);record&®istration.enqueue(record)}}}}function JsMutationObserver(callback){this.callback_=callback,this.nodes_=[],this.records_=[],this.uid_=++uidCounter}function MutationRecord(type,target){this.type=type,this.target=target,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function copyMutationRecord(original){var record=new MutationRecord(original.type,original.target);return record.addedNodes=original.addedNodes.slice(),record.removedNodes=original.removedNodes.slice(),record.previousSibling=original.previousSibling,record.nextSibling=original.nextSibling,record.attributeName=original.attributeName,record.attributeNamespace=original.attributeNamespace,record.oldValue=original.oldValue,record}function getRecord(type,target){return currentRecord=new MutationRecord(type,target)}function getRecordWithOldValue(oldValue){return recordWithOldValue?recordWithOldValue:(recordWithOldValue=copyMutationRecord(currentRecord),recordWithOldValue.oldValue=oldValue,recordWithOldValue)}function clearRecords(){currentRecord=recordWithOldValue=void 0}function recordRepresentsCurrentMutation(record){return record===recordWithOldValue||record===currentRecord}function selectRecord(lastRecord,newRecord){return lastRecord===newRecord?lastRecord:recordWithOldValue&&recordRepresentsCurrentMutation(lastRecord)?recordWithOldValue:null}function Registration(observer,target,options){this.observer=observer,this.target=target,this.options=options,this.transientObservedNodes=[]}var setImmediate,registrationsTable=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))setImmediate=setTimeout;else if(window.setImmediate)setImmediate=window.setImmediate;else{var setImmediateQueue=[],sentinel=String(Math.random());window.addEventListener("message",function(e){if(e.data===sentinel){var queue=setImmediateQueue;setImmediateQueue=[],queue.forEach(function(func){func()})}}),setImmediate=function(func){setImmediateQueue.push(func),window.postMessage(sentinel,"*")}}var isScheduled=!1,scheduledObservers=[],uidCounter=0;JsMutationObserver.prototype={observe:function(target,options){if(target=wrapIfNeeded(target),!options.childList&&!options.attributes&&!options.characterData||options.attributeOldValue&&!options.attributes||options.attributeFilter&&options.attributeFilter.length&&!options.attributes||options.characterDataOldValue&&!options.characterData)throw new SyntaxError;var registrations=registrationsTable.get(target);registrations||registrationsTable.set(target,registrations=[]);for(var registration,i=0;i<registrations.length;i++)if(registrations[i].observer===this){registration=registrations[i],registration.removeListeners(),registration.options=options;break}registration||(registration=new Registration(this,target,options),registrations.push(registration),this.nodes_.push(target)),registration.addListeners()},disconnect:function(){this.nodes_.forEach(function(node){for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++){var registration=registrations[i];if(registration.observer===this){registration.removeListeners(),registrations.splice(i,1);break}}},this),this.records_=[]},takeRecords:function(){var copyOfRecords=this.records_;return this.records_=[],copyOfRecords}};var currentRecord,recordWithOldValue;Registration.prototype={enqueue:function(record){var records=this.observer.records_,length=records.length;if(records.length>0){var lastRecord=records[length-1],recordToReplaceLast=selectRecord(lastRecord,record);if(recordToReplaceLast)return void(records[length-1]=recordToReplaceLast)}else scheduleCallback(this.observer);records[length]=record},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(node){var options=this.options;options.attributes&&node.addEventListener("DOMAttrModified",this,!0),options.characterData&&node.addEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.addEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(node){var options=this.options;options.attributes&&node.removeEventListener("DOMAttrModified",this,!0),options.characterData&&node.removeEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.removeEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(node){if(node!==this.target){this.addListeners_(node),this.transientObservedNodes.push(node);var registrations=registrationsTable.get(node);registrations||registrationsTable.set(node,registrations=[]),registrations.push(this)}},removeTransientObservers:function(){var transientObservedNodes=this.transientObservedNodes;this.transientObservedNodes=[],transientObservedNodes.forEach(function(node){this.removeListeners_(node);for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++)if(registrations[i]===this){registrations.splice(i,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var name=e.attrName,namespace=e.relatedNode.namespaceURI,target=e.target,record=new getRecord("attributes",target);record.attributeName=name,record.attributeNamespace=namespace;var oldValue=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return!options.attributes||options.attributeFilter&&options.attributeFilter.length&&-1===options.attributeFilter.indexOf(name)&&-1===options.attributeFilter.indexOf(namespace)?void 0:options.attributeOldValue?getRecordWithOldValue(oldValue):record});break;case"DOMCharacterDataModified":var target=e.target,record=getRecord("characterData",target),oldValue=e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return options.characterData?options.characterDataOldValue?getRecordWithOldValue(oldValue):record:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var addedNodes,removedNodes,changedNode=e.target;"DOMNodeInserted"===e.type?(addedNodes=[changedNode],removedNodes=[]):(addedNodes=[],removedNodes=[changedNode]);var previousSibling=changedNode.previousSibling,nextSibling=changedNode.nextSibling,record=getRecord("childList",e.target.parentNode);record.addedNodes=addedNodes,record.removedNodes=removedNodes,record.previousSibling=previousSibling,record.nextSibling=nextSibling,forEachAncestorAndObserverEnqueueRecord(e.relatedNode,function(options){return options.childList?record:void 0})}clearRecords()}},global.JsMutationObserver=JsMutationObserver,global.MutationObserver||(global.MutationObserver=JsMutationObserver)}(this),window.CustomElements=window.CustomElements||{flags:{}},function(scope){var flags=scope.flags,modules=[],addModule=function(module){modules.push(module)},initializeModules=function(){modules.forEach(function(module){module(scope)})};scope.addModule=addModule,scope.initializeModules=initializeModules,scope.hasNative=Boolean(document.registerElement),scope.useNative=!flags.register&&scope.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(scope){function forSubtree(node,cb){findAllElements(node,function(e){return cb(e)?!0:void forRoots(e,cb)}),forRoots(node,cb)}function findAllElements(node,find,data){var e=node.firstElementChild;if(!e)for(e=node.firstChild;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;for(;e;)find(e,data)!==!0&&findAllElements(e,find,data),e=e.nextElementSibling;return null}function forRoots(node,cb){for(var root=node.shadowRoot;root;)forSubtree(root,cb),root=root.olderShadowRoot}function forDocumentTree(doc,cb){_forDocumentTree(doc,cb,[])}function _forDocumentTree(doc,cb,processingDocuments){if(doc=wrap(doc),!(processingDocuments.indexOf(doc)>=0)){processingDocuments.push(doc);for(var n,imports=doc.querySelectorAll("link[rel="+IMPORT_LINK_TYPE+"]"),i=0,l=imports.length;l>i&&(n=imports[i]);i++)n["import"]&&_forDocumentTree(n["import"],cb,processingDocuments);cb(doc)}}var IMPORT_LINK_TYPE=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";scope.forDocumentTree=forDocumentTree,scope.forSubtree=forSubtree}),window.CustomElements.addModule(function(scope){function addedNode(node){return added(node)||addedSubtree(node)}function added(node){return scope.upgrade(node)?!0:void attached(node)}function addedSubtree(node){forSubtree(node,function(e){return added(e)?!0:void 0})}function attachedNode(node){attached(node),inDocument(node)&&forSubtree(node,function(e){attached(e)})}function deferMutation(fn){pendingMutations.push(fn),isPendingMutations||(isPendingMutations=!0,setTimeout(takeMutations))}function takeMutations(){isPendingMutations=!1;for(var p,$p=pendingMutations,i=0,l=$p.length;l>i&&(p=$p[i]);i++)p();pendingMutations=[]}function attached(element){hasPolyfillMutations?deferMutation(function(){_attached(element)}):_attached(element)}function _attached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&!element.__attached&&inDocument(element)&&(element.__attached=!0,element.attachedCallback&&element.attachedCallback())}function detachedNode(node){detached(node),forSubtree(node,function(e){detached(e)})}function detached(element){hasPolyfillMutations?deferMutation(function(){_detached(element)}):_detached(element)}function _detached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&element.__attached&&!inDocument(element)&&(element.__attached=!1,element.detachedCallback&&element.detachedCallback())}function inDocument(element){for(var p=element,doc=wrap(document);p;){if(p==doc)return!0;p=p.parentNode||p.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&p.host}}function watchShadow(node){if(node.shadowRoot&&!node.shadowRoot.__watched){flags.dom&&console.log("watching shadow-root for: ",node.localName);for(var root=node.shadowRoot;root;)observe(root),root=root.olderShadowRoot}}function handler(mutations){if(flags.dom){var mx=mutations[0];if(mx&&"childList"===mx.type&&mx.addedNodes&&mx.addedNodes){for(var d=mx.addedNodes[0];d&&d!==document&&!d.host;)d=d.parentNode;var u=d&&(d.URL||d._URL||d.host&&d.host.localName)||"";u=u.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",mutations.length,u||"")}mutations.forEach(function(mx){"childList"===mx.type&&(forEach(mx.addedNodes,function(n){n.localName&&addedNode(n)}),forEach(mx.removedNodes,function(n){n.localName&&detachedNode(n)}))}),flags.dom&&console.groupEnd()}function takeRecords(node){for(node=wrap(node),node||(node=wrap(document));node.parentNode;)node=node.parentNode;var observer=node.__observer;observer&&(handler(observer.takeRecords()),takeMutations())}function observe(inRoot){if(!inRoot.__observer){var observer=new MutationObserver(handler);observer.observe(inRoot,{childList:!0,subtree:!0}),inRoot.__observer=observer}}function upgradeDocument(doc){doc=wrap(doc),flags.dom&&console.group("upgradeDocument: ",doc.baseURI.split("/").pop()),addedNode(doc),observe(doc),flags.dom&&console.groupEnd()}function upgradeDocumentTree(doc){forDocumentTree(doc,upgradeDocument)}var flags=scope.flags,forSubtree=scope.forSubtree,forDocumentTree=scope.forDocumentTree,hasPolyfillMutations=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;scope.hasPolyfillMutations=hasPolyfillMutations;var isPendingMutations=!1,pendingMutations=[],forEach=Array.prototype.forEach.call.bind(Array.prototype.forEach),originalCreateShadowRoot=Element.prototype.createShadowRoot;originalCreateShadowRoot&&(Element.prototype.createShadowRoot=function(){var root=originalCreateShadowRoot.call(this);return CustomElements.watchShadow(this),root}),scope.watchShadow=watchShadow,scope.upgradeDocumentTree=upgradeDocumentTree,scope.upgradeSubtree=addedSubtree,scope.upgradeAll=addedNode,scope.attachedNode=attachedNode,scope.takeRecords=takeRecords}),window.CustomElements.addModule(function(scope){function upgrade(node){if(!node.__upgraded__&&node.nodeType===Node.ELEMENT_NODE){var is=node.getAttribute("is"),definition=scope.getRegisteredDefinition(is||node.localName);if(definition){if(is&&definition.tag==node.localName)return upgradeWithDefinition(node,definition);if(!is&&!definition["extends"])return upgradeWithDefinition(node,definition)}}}function upgradeWithDefinition(element,definition){return flags.upgrade&&console.group("upgrade:",element.localName),definition.is&&element.setAttribute("is",definition.is),implementPrototype(element,definition),element.__upgraded__=!0,created(element),scope.attachedNode(element),scope.upgradeSubtree(element),flags.upgrade&&console.groupEnd(),element}function implementPrototype(element,definition){Object.__proto__?element.__proto__=definition.prototype:(customMixin(element,definition.prototype,definition["native"]),element.__proto__=definition.prototype)}function customMixin(inTarget,inSrc,inNative){for(var used={},p=inSrc;p!==inNative&&p!==HTMLElement.prototype;){for(var k,keys=Object.getOwnPropertyNames(p),i=0;k=keys[i];i++)used[k]||(Object.defineProperty(inTarget,k,Object.getOwnPropertyDescriptor(p,k)),used[k]=1);p=Object.getPrototypeOf(p)}}function created(element){element.createdCallback&&element.createdCallback()}var flags=scope.flags;scope.upgrade=upgrade,scope.upgradeWithDefinition=upgradeWithDefinition,scope.implementPrototype=implementPrototype}),window.CustomElements.addModule(function(scope){function register(name,options){var definition=options||{};if(!name)throw new Error("document.registerElement: first argument `name` must not be empty");if(name.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(name)+"'.");if(isReservedTag(name))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(name)+"'. The type name is invalid.");if(getRegisteredDefinition(name))throw new Error("DuplicateDefinitionError: a type with name '"+String(name)+"' is already registered");return definition.prototype||(definition.prototype=Object.create(HTMLElement.prototype)),definition.__name=name.toLowerCase(),definition.lifecycle=definition.lifecycle||{},definition.ancestry=ancestry(definition["extends"]),resolveTagName(definition),resolvePrototypeChain(definition),overrideAttributeApi(definition.prototype),registerDefinition(definition.__name,definition),definition.ctor=generateConstructor(definition),definition.ctor.prototype=definition.prototype,definition.prototype.constructor=definition.ctor,scope.ready&&upgradeDocumentTree(document),definition.ctor}function overrideAttributeApi(prototype){if(!prototype.setAttribute._polyfilled){var setAttribute=prototype.setAttribute;prototype.setAttribute=function(name,value){changeAttribute.call(this,name,value,setAttribute)};var removeAttribute=prototype.removeAttribute;prototype.removeAttribute=function(name){changeAttribute.call(this,name,null,removeAttribute)},prototype.setAttribute._polyfilled=!0}}function changeAttribute(name,value,operation){name=name.toLowerCase();var oldValue=this.getAttribute(name);operation.apply(this,arguments);var newValue=this.getAttribute(name);this.attributeChangedCallback&&newValue!==oldValue&&this.attributeChangedCallback(name,oldValue,newValue)}function isReservedTag(name){for(var i=0;i<reservedTagList.length;i++)if(name===reservedTagList[i])return!0}function ancestry(extnds){var extendee=getRegisteredDefinition(extnds);return extendee?ancestry(extendee["extends"]).concat([extendee]):[]}function resolveTagName(definition){for(var a,baseTag=definition["extends"],i=0;a=definition.ancestry[i];i++)baseTag=a.is&&a.tag;definition.tag=baseTag||definition.__name,baseTag&&(definition.is=definition.__name)}function resolvePrototypeChain(definition){if(!Object.__proto__){var nativePrototype=HTMLElement.prototype;if(definition.is){var inst=document.createElement(definition.tag),expectedPrototype=Object.getPrototypeOf(inst);expectedPrototype===definition.prototype&&(nativePrototype=expectedPrototype)}for(var ancestor,proto=definition.prototype;proto&&proto!==nativePrototype;)ancestor=Object.getPrototypeOf(proto),proto.__proto__=ancestor,proto=ancestor;definition["native"]=nativePrototype}}function instantiate(definition){return upgradeWithDefinition(domCreateElement(definition.tag),definition)}function getRegisteredDefinition(name){return name?registry[name.toLowerCase()]:void 0}function registerDefinition(name,definition){registry[name]=definition}function generateConstructor(definition){return function(){return instantiate(definition)}}function createElementNS(namespace,tag,typeExtension){return namespace===HTML_NAMESPACE?createElement(tag,typeExtension):domCreateElementNS(namespace,tag)}function createElement(tag,typeExtension){tag&&(tag=tag.toLowerCase()),typeExtension&&(typeExtension=typeExtension.toLowerCase());var definition=getRegisteredDefinition(typeExtension||tag);if(definition){if(tag==definition.tag&&typeExtension==definition.is)return new definition.ctor;if(!typeExtension&&!definition.is)return new definition.ctor}var element;return typeExtension?(element=createElement(tag),element.setAttribute("is",typeExtension),element):(element=domCreateElement(tag),tag.indexOf("-")>=0&&implementPrototype(element,HTMLElement),element)}function wrapDomMethodToForceUpgrade(obj,methodName){var orig=obj[methodName];obj[methodName]=function(){var n=orig.apply(this,arguments);return upgradeAll(n),n}}var isInstance,isIE11OrOlder=scope.isIE11OrOlder,upgradeDocumentTree=scope.upgradeDocumentTree,upgradeAll=scope.upgradeAll,upgradeWithDefinition=scope.upgradeWithDefinition,implementPrototype=scope.implementPrototype,useNative=scope.useNative,reservedTagList=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],registry={},HTML_NAMESPACE="http://www.w3.org/1999/xhtml",domCreateElement=document.createElement.bind(document),domCreateElementNS=document.createElementNS.bind(document);isInstance=Object.__proto__||useNative?function(obj,base){return obj instanceof base}:function(obj,ctor){for(var p=obj;p;){if(p===ctor.prototype)return!0;p=p.__proto__}return!1},wrapDomMethodToForceUpgrade(Node.prototype,"cloneNode"),wrapDomMethodToForceUpgrade(document,"importNode"),isIE11OrOlder&&!function(){var importNode=document.importNode;document.importNode=function(){var n=importNode.apply(document,arguments);if(n.nodeType==n.DOCUMENT_FRAGMENT_NODE){var f=document.createDocumentFragment();return f.appendChild(n),f}return n}}(),document.registerElement=register,document.createElement=createElement,document.createElementNS=createElementNS,scope.registry=registry,scope["instanceof"]=isInstance,scope.reservedTagList=reservedTagList,scope.getRegisteredDefinition=getRegisteredDefinition,document.register=document.registerElement}),function(scope){function bootstrap(){upgradeDocumentTree(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(elt){upgradeDocumentTree(wrap(elt["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var useNative=scope.useNative,initializeModules=scope.initializeModules,isIE11OrOlder=/Trident/.test(navigator.userAgent);if(useNative){var nop=function(){};scope.watchShadow=nop,scope.upgrade=nop,scope.upgradeAll=nop,scope.upgradeDocumentTree=nop,scope.upgradeSubtree=nop,scope.takeRecords=nop,scope["instanceof"]=function(obj,base){return obj instanceof base}}else initializeModules();var upgradeDocumentTree=scope.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(node){return node}),isIE11OrOlder&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(inType,params){params=params||{};var e=document.createEvent("CustomEvent");return e.initCustomEvent(inType,Boolean(params.bubbles),Boolean(params.cancelable),params.detail),e},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||scope.flags.eager)bootstrap();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var loadEvent=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(loadEvent,bootstrap)}else bootstrap();scope.isIE11OrOlder=isIE11OrOlder}(window.CustomElements),window.CustomEvent||!function(){var CustomEvent;CustomEvent=function(event,params){var evt;return params=params||{bubbles:!1,cancelable:!1,detail:void 0},evt=document.createEvent("CustomEvent"),evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail),evt},CustomEvent.prototype=window.Event.prototype,window.CustomEvent=CustomEvent}(),function(){"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function(){var initializing=!1,fnTest=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(prop){function Class(){!initializing&&this.init&&this.init.apply(this,arguments)}var _super=this.prototype;initializing=!0;var prototype=new this;initializing=!1;for(var name in prop)prototype[name]="function"==typeof prop[name]&&"function"==typeof _super[name]&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);return this._super=tmp,ret}}(name,prop[name]):prop[name];return Class.prototype=prototype,Class.prototype.constructor=Class,Class.extend=arguments.callee,Class}}(),"document"in self&&("classList"in document.createElement("_")&&(!document.createElementNS||"classList"in document.createElementNS("http://www.w3.org/2000/svg","g"))?!function(){"use strict";var testElement=document.createElement("_");if(testElement.classList.add("c1","c2"),!testElement.classList.contains("c2")){var createMethod=function(method){var original=DOMTokenList.prototype[method];DOMTokenList.prototype[method]=function(token){var i,len=arguments.length;for(i=0;len>i;i++)token=arguments[i],original.call(this,token)}};createMethod("add"),createMethod("remove")}if(testElement.classList.toggle("c3",!1),testElement.classList.contains("c3")){var _toggle=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(token,force){return 1 in arguments&&!this.contains(token)==!force?force:_toggle.call(this,token)}}testElement=null}():!function(view){"use strict";if("Element"in view){var classListProp="classList",protoProp="prototype",elemCtrProto=view.Element[protoProp],objCtr=Object,strTrim=String[protoProp].trim||function(){return this.replace(/^\s+|\s+$/g,"")},arrIndexOf=Array[protoProp].indexOf||function(item){for(var i=0,len=this.length;len>i;i++)if(i in this&&this[i]===item)return i;return-1},DOMEx=function(type,message){this.name=type,this.code=DOMException[type],this.message=message},checkTokenAndGetIndex=function(classList,token){if(""===token)throw new DOMEx("SYNTAX_ERR","An invalid or illegal string was specified");if(/\s/.test(token))throw new DOMEx("INVALID_CHARACTER_ERR","String contains an invalid character");return arrIndexOf.call(classList,token)},ClassList=function(elem){for(var trimmedClasses=strTrim.call(elem.getAttribute("class")||""),classes=trimmedClasses?trimmedClasses.split(/\s+/):[],i=0,len=classes.length;len>i;i++)this.push(classes[i]);this._updateClassName=function(){elem.setAttribute("class",this.toString())}},classListProto=ClassList[protoProp]=[],classListGetter=function(){return new ClassList(this)};if(DOMEx[protoProp]=Error[protoProp],classListProto.item=function(i){return this[i]||null},classListProto.contains=function(token){return token+="",-1!==checkTokenAndGetIndex(this,token)},classListProto.add=function(){var token,tokens=arguments,i=0,l=tokens.length,updated=!1;do token=tokens[i]+"",-1===checkTokenAndGetIndex(this,token)&&(this.push(token),updated=!0);while(++i<l);updated&&this._updateClassName()},classListProto.remove=function(){var token,index,tokens=arguments,i=0,l=tokens.length,updated=!1;do for(token=tokens[i]+"",index=checkTokenAndGetIndex(this,token);-1!==index;)this.splice(index,1),updated=!0,index=checkTokenAndGetIndex(this,token);while(++i<l);updated&&this._updateClassName()},classListProto.toggle=function(token,force){token+="";var result=this.contains(token),method=result?force!==!0&&"remove":force!==!1&&"add";return method&&this[method](token),force===!0||force===!1?force:!result},classListProto.toString=function(){return this.join(" ")},objCtr.defineProperty){var classListPropDesc={get:classListGetter,enumerable:!0,configurable:!0};try{objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc)}catch(ex){-2146823252===ex.number&&(classListPropDesc.enumerable=!1,objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc))}}else objCtr[protoProp].__defineGetter__&&elemCtrProto.__defineGetter__(classListProp,classListGetter)}}(self)),function(){"use strict";function FastClick(layer,options){function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;if(options=options||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=options.touchBoundary||10,this.layer=layer,this.tapDelay=options.tapDelay||200,this.tapTimeout=options.tapTimeout||700,!FastClick.notNeeded(layer)){for(var methods=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],context=this,i=0,l=methods.length;l>i;i++)context[methods[i]]=bind(context[methods[i]],context);deviceIsAndroid&&(layer.addEventListener("mouseover",this.onMouse,!0),layer.addEventListener("mousedown",this.onMouse,!0),layer.addEventListener("mouseup",this.onMouse,!0)),layer.addEventListener("click",this.onClick,!0),layer.addEventListener("touchstart",this.onTouchStart,!1),layer.addEventListener("touchmove",this.onTouchMove,!1),layer.addEventListener("touchend",this.onTouchEnd,!1),layer.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null)}}var deviceIsWindowsPhone=navigator.userAgent.indexOf("Windows Phone")>=0,deviceIsAndroid=navigator.userAgent.indexOf("Android")>0&&!deviceIsWindowsPhone,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent)&&!deviceIsWindowsPhone,deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS [6-7]_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(target){switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type&&"month"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier&&touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,
this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1&&event.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(event){var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1)return this.cancelNextClick=!0,!0;if(event.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(event){var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1),layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){var metaViewport,chromeVersion,blackberryVersion,firefoxVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(blackberryVersion=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),blackberryVersion[1]>=10&&blackberryVersion[2]>=3&&(metaViewport=document.querySelector("meta[name=viewport]")))){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===layer.style.msTouchAction||"manipulation"===layer.style.touchAction?!0:(firefoxVersion=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],firefoxVersion>=27&&(metaViewport=document.querySelector("meta[name=viewport]"),metaViewport&&(-1!==metaViewport.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===layer.style.touchAction||"manipulation"===layer.style.touchAction?!0:!1)},FastClick.attach=function(layer,options){return new FastClick(layer,options)},window.FastClick=FastClick}();var MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),!function(e,t,n){function r(e,t){return typeof e===t}function o(){var e,t,n,o,i,s,a;for(var l in S)if(S.hasOwnProperty(l)){if(e=[],t=S[l],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;n<t.options.aliases.length;n++)e.push(t.options.aliases[n].toLowerCase());for(o=r(t.fn,"function")?t.fn():t.fn,i=0;i<e.length;i++)s=e[i],a=s.split("."),1===a.length?Modernizr[a[0]]=o:(!Modernizr[a[0]]||Modernizr[a[0]]instanceof Boolean||(Modernizr[a[0]]=new Boolean(Modernizr[a[0]])),Modernizr[a[0]][a[1]]=o),C.push((o?"":"no-")+a.join("-"))}}function i(e){var t=w.className,n=Modernizr._config.classPrefix||"";if(_&&(t=t.baseVal),Modernizr._config.enableJSClass){var r=new RegExp("(^|\\s)"+n+"no-js(\\s|$)");t=t.replace(r,"$1"+n+"js$2")}Modernizr._config.enableClasses&&(t+=" "+n+e.join(" "+n),_?w.className.baseVal=t:w.className=t)}function s(e,t){if("object"==typeof e)for(var n in e)N(e,n)&&s(n,e[n]);else{e=e.toLowerCase();var r=e.split("."),o=Modernizr[r[0]];if(2==r.length&&(o=o[r[1]]),"undefined"!=typeof o)return Modernizr;t="function"==typeof t?t():t,1==r.length?Modernizr[r[0]]=t:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=t),i([(t&&0!=t?"":"no-")+r.join("-")]),Modernizr._trigger(e,t)}return Modernizr}function a(){return"function"!=typeof t.createElement?t.createElement(arguments[0]):_?t.createElementNS.call(t,"http://www.w3.org/2000/svg",arguments[0]):t.createElement.apply(t,arguments)}function l(e,t){return!!~(""+e).indexOf(t)}function u(){var e=t.body;return e||(e=a(_?"svg":"body"),e.fake=!0),e}function f(e,n,r,o){var i,s,l,f,c="modernizr",d=a("div"),p=u();if(parseInt(r,10))for(;r--;)l=a("div"),l.id=o?o[r]:c+(r+1),d.appendChild(l);return i=a("style"),i.type="text/css",i.id="s"+c,(p.fake?p:d).appendChild(i),p.appendChild(d),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(t.createTextNode(e)),d.id=c,p.fake&&(p.style.background="",p.style.overflow="hidden",f=w.style.overflow,w.style.overflow="hidden",w.appendChild(p)),s=n(d,e),p.fake?(p.parentNode.removeChild(p),w.style.overflow=f,w.offsetHeight):d.parentNode.removeChild(d),!!s}function c(e){return e.replace(/([a-z])-([a-z])/g,function(e,t,n){return t+n.toUpperCase()}).replace(/^-/,"")}function d(e,t){return function(){return e.apply(t,arguments)}}function p(e,t,n){var o;for(var i in e)if(e[i]in t)return n===!1?e[i]:(o=t[e[i]],r(o,"function")?d(o,n||t):o);return!1}function m(e){return e.replace(/([A-Z])/g,function(e,t){return"-"+t.toLowerCase()}).replace(/^ms-/,"-ms-")}function h(t,r){var o=t.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;)if(e.CSS.supports(m(t[o]),r))return!0;return!1}if("CSSSupportsRule"in e){for(var i=[];o--;)i.push("("+m(t[o])+":"+r+")");return i=i.join(" or "),f("@supports ("+i+") { #modernizr { position: absolute; } }",function(e){return"absolute"==getComputedStyle(e,null).position})}return n}function g(e,t,o,i){function s(){f&&(delete L.style,delete L.modElem)}if(i=r(i,"undefined")?!1:i,!r(o,"undefined")){var u=h(e,o);if(!r(u,"undefined"))return u}for(var f,d,p,m,g,v=["modernizr","tspan"];!L.style;)f=!0,L.modElem=a(v.shift()),L.style=L.modElem.style;for(p=e.length,d=0;p>d;d++)if(m=e[d],g=L.style[m],l(m,"-")&&(m=c(m)),L.style[m]!==n){if(i||r(o,"undefined"))return s(),"pfx"==t?m:!0;try{L.style[m]=o}catch(y){}if(L.style[m]!=g)return s(),"pfx"==t?m:!0}return s(),!1}function v(e,t,n,o,i){var s=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+k.join(s+" ")+s).split(" ");return r(t,"string")||r(t,"undefined")?g(a,t,o,i):(a=(e+" "+T.join(s+" ")+s).split(" "),p(a,t,n))}function y(e,t,r){return v(e,n,n,t,r)}var C=[],S=[],x={_version:"3.1.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function(e,t,n){S.push({name:e,fn:t,options:n})},addAsyncTest:function(e){S.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=x,Modernizr=new Modernizr,Modernizr.addTest("svg",!!t.createElementNS&&!!t.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect);var b=x._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):[];x._prefixes=b;var w=t.documentElement,_="svg"===w.nodeName.toLowerCase();_||!function(e,t){function n(e,t){var n=e.createElement("p"),r=e.getElementsByTagName("head")[0]||e.documentElement;return n.innerHTML="x<style>"+t+"</style>",r.insertBefore(n.lastChild,r.firstChild)}function r(){var e=C.elements;return"string"==typeof e?e.split(" "):e}function o(e,t){var n=C.elements;"string"!=typeof n&&(n=n.join(" ")),"string"!=typeof e&&(e=e.join(" ")),C.elements=n+" "+e,u(t)}function i(e){var t=y[e[g]];return t||(t={},v++,e[g]=v,y[v]=t),t}function s(e,n,r){if(n||(n=t),c)return n.createElement(e);r||(r=i(n));var o;return o=r.cache[e]?r.cache[e].cloneNode():h.test(e)?(r.cache[e]=r.createElem(e)).cloneNode():r.createElem(e),!o.canHaveChildren||m.test(e)||o.tagUrn?o:r.frag.appendChild(o)}function a(e,n){if(e||(e=t),c)return e.createDocumentFragment();n=n||i(e);for(var o=n.frag.cloneNode(),s=0,a=r(),l=a.length;l>s;s++)o.createElement(a[s]);return o}function l(e,t){t.cache||(t.cache={},t.createElem=e.createElement,t.createFrag=e.createDocumentFragment,t.frag=t.createFrag()),e.createElement=function(n){return C.shivMethods?s(n,e,t):t.createElem(n)},e.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+r().join().replace(/[\w\-:]+/g,function(e){return t.createElem(e),t.frag.createElement(e),'c("'+e+'")'})+");return n}")(C,t.frag)}function u(e){e||(e=t);var r=i(e);return!C.shivCSS||f||r.hasCSS||(r.hasCSS=!!n(e,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),c||l(e,r),e}var f,c,d="3.7.3",p=e.html5||{},m=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,h=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g="_html5shiv",v=0,y={};!function(){try{var e=t.createElement("a");e.innerHTML="<xyz></xyz>",f="hidden"in e,c=1==e.childNodes.length||function(){t.createElement("a");var e=t.createDocumentFragment();return"undefined"==typeof e.cloneNode||"undefined"==typeof e.createDocumentFragment||"undefined"==typeof e.createElement}()}catch(n){f=!0,c=!0}}();var C={elements:p.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:d,shivCSS:p.shivCSS!==!1,supportsUnknownElements:c,shivMethods:p.shivMethods!==!1,type:"default",shivDocument:u,createElement:s,createDocumentFragment:a,addElements:o};e.html5=C,u(t),"object"==typeof module&&module.exports&&(module.exports=C)}("undefined"!=typeof e?e:this,t);var E="Moz O ms Webkit",T=x._config.usePrefixes?E.toLowerCase().split(" "):[];x._domPrefixes=T;var N;!function(){var e={}.hasOwnProperty;N=r(e,"undefined")||r(e.call,"undefined")?function(e,t){return t in e&&r(e.constructor.prototype[t],"undefined")}:function(t,n){return e.call(t,n)}}(),x._l={},x.on=function(e,t){this._l[e]||(this._l[e]=[]),this._l[e].push(t),Modernizr.hasOwnProperty(e)&&setTimeout(function(){Modernizr._trigger(e,Modernizr[e])},0)},x._trigger=function(e,t){if(this._l[e]){var n=this._l[e];setTimeout(function(){var e,r;for(e=0;e<n.length;e++)(r=n[e])(t)},0),delete this._l[e]}},Modernizr._q.push(function(){x.addTest=s}),Modernizr.addTest("canvas",function(){var e=a("canvas");return!(!e.getContext||!e.getContext("2d"))});var P="CSS"in e&&"supports"in e.CSS,j="supportsCSS"in e;Modernizr.addTest("supports",P||j);var k=x._config.usePrefixes?E.split(" "):[];x._cssomPrefixes=k;var z=x.testStyles=f,F={elem:a("modernizr")};Modernizr._q.push(function(){delete F.elem});var L={style:F.elem.style};Modernizr._q.unshift(function(){delete L.style}),x.testProp=function(e,t,r){return g([e],n,t,r)},x.testAllProps=v,x.testAllProps=y,Modernizr.addTest("borderradius",y("borderRadius","0px",!0)),Modernizr.addTest("boxshadow",y("boxShadow","1px 1px",!0)),Modernizr.addTest("cssanimations",y("animationName","a",!0)),Modernizr.addTest("csstransforms",function(){return-1===navigator.userAgent.indexOf("Android 2.")&&y("transform","scale(1)",!0)}),Modernizr.addTest("csstransforms3d",function(){var e=!!y("perspective","1px",!0),t=Modernizr._config.usePrefixes;if(e&&(!t||"webkitPerspective"in w.style)){var n;Modernizr.supports?n="@supports (perspective: 1px)":(n="@media (transform-3d)",t&&(n+=",(-webkit-transform-3d)")),n+="{#modernizr{left:9px;position:absolute;height:5px;margin:0;padding:0;border:0}}",z(n,function(t){e=9===t.offsetLeft&&5===t.offsetHeight})}return e}),Modernizr.addTest("csstransitions",y("transition","all",!0)),o(),i(C),delete x.addTest,delete x.addAsyncTest;for(var A=0;A<Modernizr._q.length;A++)Modernizr._q[A]();e.Modernizr=Modernizr}(window,document),!function n(t,e,r){function o(u,f){if(!e[u]){if(!t[u]){var c="function"==typeof require&&require;if(!f&&c)return c(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var l=e[u]={exports:{}};t[u][0].call(l.exports,function(n){var e=t[u][1][n];return o(e?e:n)},l,l.exports,n,t,e,r)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(n,t,e){"use strict";function r(){}function o(n){try{return n.then}catch(t){return d=t,w}}function i(n,t){try{return n(t)}catch(e){return d=e,w}}function u(n,t,e){try{n(t,e)}catch(r){return d=r,w}}function f(n){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof n)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],n!==r&&v(n,this)}function c(n,t,e){return new n.constructor(function(o,i){var u=new f(r);u.then(o,i),s(n,new p(t,e,u))})}function s(n,t){for(;3===n._37;)n=n._12;return 0===n._37?void n._59.push(t):void y(function(){var e=1===n._37?t.onFulfilled:t.onRejected;if(null===e)return void(1===n._37?l(t.promise,n._12):a(t.promise,n._12));var r=i(e,n._12);r===w?a(t.promise,d):l(t.promise,r)})}function l(n,t){if(t===n)return a(n,new TypeError("A promise cannot be resolved with itself."));if(t&&("object"==typeof t||"function"==typeof t)){var e=o(t);if(e===w)return a(n,d);if(e===n.then&&t instanceof f)return n._37=3,n._12=t,void h(n);if("function"==typeof e)return void v(e.bind(t),n)}n._37=1,n._12=t,h(n)}function a(n,t){n._37=2,n._12=t,h(n)}function h(n){for(var t=0;t<n._59.length;t++)s(n,n._59[t]);n._59=null}function p(n,t,e){this.onFulfilled="function"==typeof n?n:null,this.onRejected="function"==typeof t?t:null,this.promise=e}function v(n,t){var e=!1,r=u(n,function(n){e||(e=!0,l(t,n))},function(n){e||(e=!0,a(t,n))});e||r!==w||(e=!0,a(t,d))}var y=n("asap/raw"),d=null,w={};t.exports=f,f._99=r,f.prototype.then=function(n,t){if(this.constructor!==f)return c(this,n,t);var e=new f(r);return s(this,new p(n,t,e)),e}},{"asap/raw":4}],2:[function(n,t,e){"use strict";function r(n){var t=new o(o._99);return t._37=1,t._12=n,t}var o=n("./core.js");t.exports=o;var i=r(!0),u=r(!1),f=r(null),c=r(void 0),s=r(0),l=r("");o.resolve=function(n){if(n instanceof o)return n;if(null===n)return f;if(void 0===n)return c;if(n===!0)return i;if(n===!1)return u;if(0===n)return s;if(""===n)return l;if("object"==typeof n||"function"==typeof n)try{var t=n.then;if("function"==typeof t)return new o(t.bind(n))}catch(e){return new o(function(n,t){t(e)})}return r(n)},o.all=function(n){var t=Array.prototype.slice.call(n);return new o(function(n,e){function r(u,f){if(f&&("object"==typeof f||"function"==typeof f)){if(f instanceof o&&f.then===o.prototype.then){for(;3===f._37;)f=f._12;return 1===f._37?r(u,f._12):(2===f._37&&e(f._12),void f.then(function(n){r(u,n)},e))}var c=f.then;if("function"==typeof c){var s=new o(c.bind(f));return void s.then(function(n){r(u,n)},e)}}t[u]=f,0===--i&&n(t)}if(0===t.length)return n([]);for(var i=t.length,u=0;u<t.length;u++)r(u,t[u])})},o.reject=function(n){return new o(function(t,e){e(n)})},o.race=function(n){return new o(function(t,e){n.forEach(function(n){o.resolve(n).then(t,e)})})},o.prototype["catch"]=function(n){return this.then(null,n)}},{"./core.js":1}],3:[function(n,t,e){"use strict";function r(){if(c.length)throw c.shift()}function o(n){var t;t=f.length?f.pop():new i,t.task=n,u(t)}function i(){this.task=null}var u=n("./raw"),f=[],c=[],s=u.makeRequestCallFromTimer(r);t.exports=o,i.prototype.call=function(){try{this.task.call()}catch(n){o.onerror?o.onerror(n):(c.push(n),s())}finally{this.task=null,f[f.length]=this}}},{"./raw":4}],4:[function(n,t,e){(function(n){"use strict";function e(n){f.length||(u(),c=!0),f[f.length]=n}function r(){for(;s<f.length;){var n=s;if(s+=1,f[n].call(),s>l){for(var t=0,e=f.length-s;e>t;t++)f[t]=f[t+s];f.length-=s,s=0}}f.length=0,s=0,c=!1}function o(n){var t=1,e=new a(n),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function i(n){return function(){function t(){clearTimeout(e),clearInterval(r),n()}var e=setTimeout(t,0),r=setInterval(t,50)}}t.exports=e;var u,f=[],c=!1,s=0,l=1024,a=n.MutationObserver||n.WebKitMutationObserver;u="function"==typeof a?o(r):i(r),e.requestFlush=u,e.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(n,t,e){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(n,t){var e=arguments.length?this.then.apply(this,arguments):this;e.then(null,function(n){setTimeout(function(){throw n},0)})})},{}],6:[function(n,t,e){n("asap"),"undefined"==typeof Promise&&(Promise=n("./lib/core.js"),n("./lib/es6-extensions.js")),n("./polyfill-done.js")},{"./lib/core.js":1,"./lib/es6-extensions.js":2,"./polyfill-done.js":5,asap:3}]},{},[6]),function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(function(){return this}()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),window.animit=function(){"use strict";var TIMEOUT_RATIO=1.4,Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[]};Animit.prototype={transitionQueue:void 0,elements:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=transition.css?new Animit.Transition(transition):new Animit.Transition({css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return seconds>0&&this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},saveStyle:function(){return this.transitionQueue.push(function(done){this.elements.forEach(function(element,index){for(var css=this.lastStyleAttributeDict[index]={},i=0;i<element.style.length;i++)css[element.style[i]]=element.style[element.style[i]]}.bind(this)),done()}.bind(this)),this},restoreStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[transitionName]="none";var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var i=0,name="";i<element.style.length;i++)name=element.style[i],"undefined"==typeof css[element.style[i]]&&(css[element.style[i]]="");Object.keys(css).forEach(function(key){element.style[key]=css[key]})})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');var transitionName=util.transitionPropertyName;if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear");this.transitionQueue.push(function(done){var elements=this.elements,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),clearTransition(),done()}),timeoutId=setTimeout(function(){removeListeners(),clearTransition(),done()},1e3*options.duration*TIMEOUT_RATIO);elements.forEach(function(element,index){var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var name,i=0,len=element.style.length;len>i;i++)name=element.style[i],void 0===css[name]&&(css[name]="");element.style[transitionName]=transitionValue,Object.keys(css).forEach(function(key){key!==transitionName&&(element.style[key]=css[key])}),element.style[transitionName]=transitionValue});var clearTransition=function(){elements.forEach(function(element){element.style[transitionName]=""})}})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){var value=css[name];if(util.hasCssProperty(name))return void(result[name]=value);var prefixed=util.vendorPrefix+util.capitalize(name);util.hasCssProperty(prefixed)?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*TIMEOUT_RATIO,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element){element.style[util.transitionPropertyName]=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element){element.style[util.transitionPropertyName]="",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length>0?util.forceLayoutAtOnce(elements,function(){util.batchAnimationFrame(callback)}):util.batchAnimationFrame(callback)}:void 0}};var util={};return util.capitalize=function(str){return str.charAt(0).toUpperCase()+str.slice(1)},util.buildTransitionValue=function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},util.onceOnTransitionEnd=function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn,!1)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},util._transitionEndEvents=function(){return"ontransitionend"in window?["transitionend"]:"onwebkittransitionend"in window?["webkitTransitionEnd"]:"webkit"===util.vendorPrefix||"o"===util.vendorPrefix||"moz"===util.vendorPrefix||"ms"===util.vendorPrefix?[util.vendorPrefix+"TransitionEnd","transitionend"]:[]}(),util._cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0);return dict}(),util.hasCssProperty=function(name){return name in util._cssPropertyDict},util.vendorPrefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];
return pre}(),util.forceLayoutAtOnce=function(elements,callback){this.batchImmediate(function(){elements.forEach(function(element){element.offsetHeight}),callback()})},util.batchImmediate=function(){var callbacks=[];return function(callback){0===callbacks.length&&setImmediate(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.batchAnimationFrame=function(){var callbacks=[],raf=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,1e3/60)};return function(callback){0===callbacks.length&&raf(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.transitionPropertyName=function(){if(util.hasCssProperty("transition"))return"transition";if(util.hasCssProperty(util.vendorPrefix+"Transition"))return util.vendorPrefix+"Transition";throw new Error("Invalid state")}(),Animit}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();window.DoorLock=function(){"use strict";var generateId=function(){var i=0;return function(){return i++}}(),DoorLock=function(){function DoorLock(options){_classCallCheck(this,DoorLock),options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}}return _createClass(DoorLock,[{key:"lock",value:function(){var _this=this,unlock=function unlock(){_this._unlock(unlock)};return unlock.id=generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock}},{key:"_unlock",value:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()}},{key:"_tryToFreeWaitList",value:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()}},{key:"waitUnlock",value:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()}},{key:"isLocked",value:function(){return this._lockList.length>0}}]),DoorLock}();return DoorLock}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util={_ready:!1,_domContentLoaded:!1,_onDOMContentLoaded:function(){util._domContentLoaded=!0,ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0},addBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};window.addEventListener("DOMContentLoaded",function(){return util._onDOMContentLoaded()},!1);var HandlerRepository={_store:{},_genId:function(){var i=0;return function(){return i++}}(),set:function(element,handler){element.dataset.deviceBackButtonHandlerId&&this.remove(element);var id=element.dataset.deviceBackButtonHandlerId=HandlerRepository._genId();this._store[id]=handler},remove:function(element){element.dataset.deviceBackButtonHandlerId&&(delete this._store[element.dataset.deviceBackButtonHandlerId],delete element.dataset.deviceBackButtonHandlerId)},get:function(element){if(!element.dataset.deviceBackButtonHandlerId)return void 0;var id=element.dataset.deviceBackButtonHandlerId;if(!this._store[id])throw new Error;return this._store[id]},has:function(element){var id=element.dataset.deviceBackButtonHandlerId;return!!this._store[id]}},DeviceBackButtonDispatcher=function(){function DeviceBackButtonDispatcher(){_classCallCheck(this,DeviceBackButtonDispatcher),this._isEnabled=!1,this._boundCallback=this._callback.bind(this)}return _createClass(DeviceBackButtonDispatcher,[{key:"enable",value:function(){this._isEnabled||(util.addBackButtonListener(this._boundCallback),this._isEnabled=!0)}},{key:"disable",value:function(){this._isEnabled&&(util.removeBackButtonListener(this._boundCallback),this._isEnabled=!1)}},{key:"fireDeviceBackButtonEvent",value:function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)}},{key:"_callback",value:function(){this._dispatchDeviceBackButtonEvent()}},{key:"createHandler",value:function(element,callback){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){HandlerRepository.remove(element)},setListener:function(callback){this._callback=callback},enable:function(){HandlerRepository.set(element,this)},isEnabled:function(){return HandlerRepository.get(element)===this},destroy:function(){HandlerRepository.remove(element),this._callback=this._element=null}};return handler.enable(),handler}},{key:"_dispatchDeviceBackButtonEvent",value:function(){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parentNode;parent;){if(handler=HandlerRepository.get(parent))return handler._callback(createEvent(parent));parent=parent.parentNode}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=HandlerRepository.get(element);handler._callback(createEvent(element))}},{key:"_captureTree",value:function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],arrayOf(element.children).map(function(childElement){if("none"===childElement.style.display)return[];if(0===childElement.children.length&&!HandlerRepository.has(childElement))return[];var result=createTree(childElement);return 0!==result.children.length||HandlerRepository.has(result.element)?[result]:[]}))}}function arrayOf(target){for(var result=[],i=0;i<target.length;i++)result.push(target[i]);return result}return createTree(document.body)}},{key:"_findHandlerLeafElement",value:function(tree){function find(_x){for(var _again=!0;_again;){var node=_x;if(_again=!1,0===node.children.length)return node.element;if(1!==node.children.length)return node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(!left)return right;var leftZ=parseInt(window.getComputedStyle(left,"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right,"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null);_x=node.children[0],_again=!0}}return find(tree)}}]),DeviceBackButtonDispatcher}();ons._deviceBackButtonDispatcher=new DeviceBackButtonDispatcher,window.addEventListener("DOMContentLoaded",function(){ons._deviceBackButtonDispatcher.enable()})}(window.ons=window.ons||{}),function(ons){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}ons._readyLock=new DoorLock,ons._config={autoStatusBarFill:!0,animationsDisabled:!1},waitDeviceReady(),ons.isReady=function(){return!ons._readyLock.isLocked()},ons.isWebView=function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},ons.ready=function(callback){ons.isReady()?callback():ons._readyLock.waitUnlock(callback)},ons.setDefaultDeviceBackButtonListener=function(listener){ons._defaultDeviceBackButtonHandler.setListener(listener)},ons.disableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.disable()},ons.enableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.enable()},ons.enableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!0},ons.disableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!1},ons.disableAnimations=function(){ons._config.animationsDisabled=!0},ons.enableAnimations=function(){ons._config.animationsDisabled=!1},ons._createPopoverOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-popover/gi)?"<div>"+html+"</div>":"<ons-popover>"+html+"</ons-popover>";var div=ons._util.createElement("<div>"+html+"</div>"),popover=div.querySelector("ons-popover");return CustomElements.upgrade(popover),document.body.appendChild(popover),options.link instanceof Function&&options.link(popover),popover})},ons.createPopover=ons._createPopoverOriginal,ons._createDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-dialog/gi)?"<div>"+html+"</div>":"<ons-dialog>"+html+"</ons-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),dialog=div.querySelector("ons-dialog");return CustomElements.upgrade(dialog),document.body.appendChild(dialog),options.link instanceof Function&&options.link(dialog),dialog})},ons.createDialog=ons._createDialogOriginal,ons._createAlertDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-alert-dialog/gi)?"<div>"+html+"</div>":"<ons-alert-dialog>"+html+"</ons-alert-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),alertDialog=div.querySelector("ons-alert-dialog");return CustomElements.upgrade(alertDialog),document.body.appendChild(alertDialog),options.link instanceof Function&&options.link(alertDialog),alertDialog})},ons.createAlertDialog=ons._createAlertDialogOriginal,ons._resolveLoadingPlaceholderOriginal=function(page,link){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));if(!(elements.length>0))throw new Error("No ons-loading-placeholder exists.");elements.filter(function(element){return!element.getAttribute("page")}).forEach(function(element){element.setAttribute("ons-loading-placeholder",page),ons._resolveLoadingPlaceholder(element,page,link)})},ons.resolveLoadingPlaceholder=ons._resolveLoadingPlaceholderOriginal,ons._setupLoadingPlaceHolders=function(){ons.ready(function(){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));elements.forEach(function(element){var page=element.getAttribute("ons-loading-placeholder");"string"==typeof page&&ons._resolveLoadingPlaceholder(element,page)})})},ons._resolveLoadingPlaceholder=function(element,page,link){link=link||function(element,done){done()},ons._internal.getPageHTMLAsync(page).then(function(html){for(;element.firstChild;)element.removeChild(element.firstChild);var contentElement=ons._util.createElement("<div>"+html+"</div>");contentElement.style.display="none",element.appendChild(contentElement),link(contentElement,function(){contentElement.style.display=""})})["catch"](function(error){throw new Error("Unabled to resolve placeholder: "+error)})}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util=ons._util||{};util.findChild=function(element,query){for(var match=query instanceof Function?query:"."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},i=0;i<element.children.length;i++){var node=element.children[i];if(match(node))return node}return null},util.findParent=function(element,query){for(var match="."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},parent=element.parentNode;;){if(!parent)return null;if(match(parent))return parent;parent=parent.parentNode}},util.isAttached=function(element){for(;document.documentElement!==element;){if(!element)return!1;element=element.parentNode}return!0},util.hasAnyComponentAsParent=function(element){for(;element&&document.documentElement!==element;)if(element=element.parentNode,element&&element.nodeName.toLowerCase().match(/(ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/))return!0;return!1},util.propagateAction=function(element,action){for(var i=0;i<element.childNodes.length;i++){var child=element.childNodes[i];child[action]?child[action]():ons._util.propagateAction(child,action)}},util.createElement=function(html){var wrapper=document.createElement("div");if(wrapper.innerHTML=html,wrapper.children.length>1)throw new Error('"html" must be one wrapper element.');return wrapper.children[0]},util.createFragment=function(html){var wrapper=document.createElement("div");wrapper.innerHTML=html;var fragment=document.createDocumentFragment();return wrapper.firstChild&&fragment.appendChild(wrapper.firstChild),fragment},util.extend=function(dst){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_len>_key;_key++)args[_key-1]=arguments[_key];for(var i=0;i<args.length;i++)if(args[i])for(var keys=Object.keys(args[i]),j=0;j<keys.length;j++){var key=keys[j];dst[key]=args[i][key]}return dst},util.arrayFrom=function(arrayLike){for(var result=[],i=0;i<arrayLike.length;i++)result.push(arrayLike[i]);return result},util.parseJSONObjectSafely=function(jsonString){var failSafe=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];try{var result=JSON.parse(""+jsonString);if("object"==typeof result&&null!==result)return result}catch(e){return failSafe}return failSafe},util.triggerElementEvent=function(target,eventName){var detail=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],event=new CustomEvent(eventName,{bubbles:!0,cancelable:!0,detail:detail});return Object.keys(detail).forEach(function(key){event[key]=detail[key]}),target.dispatchEvent(event),event},util.hasModifier=function(target,modifierName){if(!target.hasAttribute("modifier"))return!1;for(var modifiers=target.getAttribute("modifier").trim().split(/\s+/),i=0;i<modifiers.length;i++)if(modifiers[i]===modifierName)return!0;return!1}}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModalAnimator=function(){function ModalAnimator(options){_classCallCheck(this,ModalAnimator),this.delay=0,this.duration=.2,options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration,this.delay=void 0!==options.delay?options.delay:this.delay}return _createClass(ModalAnimator,[{key:"show",value:function(modal,callback){callback()}},{key:"hide",value:function(modal,callback){callback()}}]),ModalAnimator}();ons._internal=ons._internal||{},ons._internal.ModalAnimator=ModalAnimator}(window.ons=window.ons||{});var _get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var SplitterAnimator=(ons._util,function(){function SplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,SplitterAnimator),options=ons._util.extend({timing:"linear",duration:"0.3",delay:"0"},options||{}),this._timing=options.timing,this._duration=options.duration,this._delay=options.delay}return _createClass(SplitterAnimator,[{key:"layoutOnOpen",value:function(){}},{key:"layoutOnClose",value:function(){}},{key:"translate",value:function(distance){}},{key:"open",value:function(done){done()}},{key:"close",value:function(done){done()}},{key:"activate",value:function(contentElement,sideElement,maskElement){}},{key:"inactivate",value:function(){}},{key:"isActivated",value:function(){throw new Error}}]),SplitterAnimator}()),OverlaySplitterAnimator=function(_SplitterAnimator){function OverlaySplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,OverlaySplitterAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .1, 1)",duration:"0.3",delay:"0"},options||{}),_get(Object.getPrototypeOf(OverlaySplitterAnimator.prototype),"constructor",this).call(this,options)}return _inherits(OverlaySplitterAnimator,_SplitterAnimator),_createClass(OverlaySplitterAnimator,[{key:"isActivated",value:function(){return this._isActivated}},{key:"layoutOnClose",value:function(){animit(this._side).queue({transform:"translateX(0%)",width:this._side._getWidth()}).play(),this._mask.style.display="none"}},{key:"layoutOnOpen",value:function(){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+"100%, 0px, 0px)",width:this._side._getWidth()}).play(),this._mask.style.display="block"}},{key:"activate",value:function(contentElement,sideElement,maskElement){this._isActivated=!0,this._content=contentElement,this._side=sideElement,this._mask=maskElement,this._setupLayout()}},{key:"inactivate",value:function(){this._isActivated=!1,this._clearLayout(),this._content=this._side=this._mask=null}},{key:"translate",value:function(distance){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+distance+"px, 0px, 0px)"}).play()}},{key:"_clearLayout",value:function(){var side=this._side,mask=this._mask;side.style.zIndex="",side.style.right="",side.style.left="",side.style.transform=side.style.webkitTransform="",side.style.transition=side.style.webkitTransition="",side.style.width="",side.style.display="",mask.style.display="none"}},{key:"_setupLayout",value:function(){var side=this._side;side.style.zIndex=3,side.style.display="block",side._isLeftSide()?(side.style.left="auto",side.style.right="100%"):(side.style.left="100%",side.style.right="auto")}},{key:"open",value:function(done){var transform=this._side._isLeftSide()?"translate3d(100%, 0px, 0px)":"translate3d(-100%, 0px, 0px)";animit.runAll(animit(this._side).wait(this._delay).queue({transform:transform},{duration:this._duration,timing:this._timing}).queue(function(callback){callback(),done()}),animit(this._mask).wait(this._delay).queue({display:"block"}).queue({opacity:"1"},{duration:this._duration,timing:"linear"}))}},{key:"close",value:function(done){var _this=this;animit.runAll(animit(this._side).wait(this._delay).queue({transform:"translate3d(0px, 0px, 0px)"},{duration:this._duration,timing:this._timing}).queue(function(callback){_this._side.style.webkitTransition="",done(),callback()}),animit(this._mask).wait(this._delay).queue({opacity:"0"},{duration:this._duration,timing:"linear"}).queue({display:"none"}))}}]),OverlaySplitterAnimator}(SplitterAnimator);ons._internal=ons._internal||{},ons._internal.SplitterAnimator=SplitterAnimator,ons._internal.OverlaySplitterAnimator=OverlaySplitterAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var NavigatorTransitionAnimator=function(){function NavigatorTransitionAnimator(options){_classCallCheck(this,NavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(NavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NavigatorTransitionAnimator}(),NoneNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function NoneNavigatorTransitionAnimator(options){_classCallCheck(this,NoneNavigatorTransitionAnimator),_get(Object.getPrototypeOf(NoneNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(NoneNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(NoneNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NoneNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.NavigatorTransitionAnimator=NavigatorTransitionAnimator,ons._internal.NoneNavigatorTransitionAnimator=NoneNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var PopoverAnimator=function(){function PopoverAnimator(options){_classCallCheck(this,PopoverAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,delay:0},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(PopoverAnimator,[{key:"show",value:function(popover,callback){callback()}},{key:"hide",value:function(popover,callback){callback()}}]),PopoverAnimator}();ons._internal=ons._internal||{},ons._internal.PopoverAnimator=PopoverAnimator}(window.ons=window.ons||{}),function(ons){"use strict";ons.platform={_renderPlatform:null,select:function(platform){ons.platform._renderPlatform=platform.trim().toLowerCase()},isWebView:function(){return ons.isWebView()},isIOS:function(){return ons.platform._renderPlatform?"ios"===ons.platform._renderPlatform:"object"==typeof device?/iOS/i.test(device.platform):/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return ons.platform._renderPlatform?"android"===ons.platform._renderPlatform:"object"==typeof device?/Android/i.test(device.platform):/Android/i.test(navigator.userAgent)},isAndroidPhone:function(){return/Android/i.test(navigator.userAgent)&&/Mobile/i.test(navigator.userAgent)},isAndroidTablet:function(){return/Android/i.test(navigator.userAgent)&&!/Mobile/i.test(navigator.userAgent)},isWP:function(){return ons.platform._renderPlatform?"wp"===ons.platform._renderPlatform:"object"==typeof device?/Win32NT|WinCE/i.test(device.platform):/Windows Phone|IEMobile|WPDesktop/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isIPod:function(){return/iPod/i.test(navigator.userAgent)},isBlackBerry:function(){return ons.platform._renderPlatform?"blackberry"===ons.platform._renderPlatform:"object"==typeof device?/BlackBerry/i.test(device.platform):/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return ons.platform._renderPlatform?"opera"===ons.platform._renderPlatform:!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return ons.platform._renderPlatform?"firefox"===ons.platform._renderPlatform:"undefined"!=typeof InstallTrigger},isSafari:function(){return ons.platform._renderPlatform?"safari"===ons.platform._renderPlatform:Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return ons.platform._renderPlatform?"chrome"===ons.platform._renderPlatform:!(!window.chrome||window.opera||navigator.userAgent.indexOf(" OPR/")>=0||navigator.userAgent.indexOf(" Edge/")>=0)},isIE:function(){return ons.platform._renderPlatform?"ie"===ons.platform._renderPlatform:!!document.documentMode},isEdge:function(){return ons.platform._renderPlatform?"edge"===ons.platform._renderPlatform:navigator.userAgent.indexOf(" Edge/")>=0},isIOS7above:function(){if("object"==typeof device)return/iOS/i.test(device.platform)&&parseInt(device.version.split(".")[0])>=7;if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1},getMobileOS:function(){return this.isAndroid()?"android":this.isIOS()?"ios":this.isWP()?"wp":"other"},getIOSDevice:function(){return this.isIPhone()?"iphone":this.isIPad()?"ipad":this.isIPod()?"ipod":"na"}}}(window.ons=window.ons||{});var _get=function(_x4,_x5,_x6){for(var _again=!0;_again;){var object=_x4,property=_x5,receiver=_x6;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x4=parent,_x5=property,_x6=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AlertDialogAnimator=function(){function AlertDialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,AlertDialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(AlertDialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),AlertDialogAnimator}(),AndroidAlertDialogAnimator=function(_AlertDialogAnimator){function AndroidAlertDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"cubic-bezier(.1, .7, .4, 1)":_ref2$timing,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.2:_ref2$duration,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay;_classCallCheck(this,AndroidAlertDialogAnimator),_get(Object.getPrototypeOf(AndroidAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(AndroidAlertDialogAnimator,_AlertDialogAnimator),_createClass(AndroidAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidAlertDialogAnimator}(AlertDialogAnimator),IOSAlertDialogAnimator=function(_AlertDialogAnimator2){function IOSAlertDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"cubic-bezier(.1, .7, .4, 1)":_ref3$timing,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.2:_ref3$duration,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay;_classCallCheck(this,IOSAlertDialogAnimator),_get(Object.getPrototypeOf(IOSAlertDialogAnimator.prototype),"constructor",this).call(this,{
duration:duration,timing:timing,delay:delay})}return _inherits(IOSAlertDialogAnimator,_AlertDialogAnimator2),_createClass(IOSAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSAlertDialogAnimator}(AlertDialogAnimator);ons._internal=ons._internal||{},ons._internal.AlertDialogAnimator=AlertDialogAnimator,ons._internal.AndroidAlertDialogAnimator=AndroidAlertDialogAnimator,ons._internal.IOSAlertDialogAnimator=IOSAlertDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AnimatorFactory=function(){function AnimatorFactory(opts){if(_classCallCheck(this,AnimatorFactory),this._animators=opts.animators,this._baseClass=opts.baseClass,this._baseClassName=opts.baseClassName||opts.baseClass.name,this._animation=opts.defaultAnimation||"default",this._animationOptions=opts.defaultAnimationOptions||{},!this._animators[this._animation])throw new Error("No such animation: "+this._animation)}return _createClass(AnimatorFactory,[{key:"setAnimationOptions",value:function(options){this._animationOptions=options}},{key:"newAnimator",value:function(options,defaultAnimator){options=options||{};var animator=null;if(options.animation instanceof this._baseClass)return options.animation;var Animator=null;if("string"==typeof options.animation&&(Animator=this._animators[options.animation]),!Animator&&defaultAnimator)animator=defaultAnimator;else{Animator=Animator||this._animators[this._animation];var animationOpts=ons._util.extend({},this._animationOptions,options.animationOptions||{},ons._config.animationsDisabled?{duration:0,delay:0}:{});animator=new Animator(animationOpts)}if(!(animator instanceof this._baseClass))throw new Error('"animator" is not an instance of '+this._baseClassName+".");return animator}}],[{key:"parseAnimationOptionsString",value:function(jsonString){try{if("string"==typeof jsonString){var result=JSON.parse(jsonString);if("object"==typeof result&&null!==result)return result;console.error('"animation-options" attribute must be a JSON object string: '+jsonString)}return{}}catch(e){return console.error('"animation-options" attribute must be a JSON object string: '+jsonString),{}}}}]),AnimatorFactory}();ons._internal=ons._internal||{},ons._internal.AnimatorFactory=AnimatorFactory}(window.ons=window.ons||{});var _get=function(_x5,_x6,_x7){for(var _again=!0;_again;){var object=_x5,property=_x6,receiver=_x7;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x5=parent,_x6=property,_x7=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var DialogAnimator=function(){function DialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,DialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(DialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),DialogAnimator}(),AndroidDialogAnimator=function(_DialogAnimator){function AndroidDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"ease-in-out":_ref2$timing,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.3:_ref2$duration;_classCallCheck(this,AndroidDialogAnimator),_get(Object.getPrototypeOf(AndroidDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(AndroidDialogAnimator,_DialogAnimator),_createClass(AndroidDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidDialogAnimator}(DialogAnimator),IOSDialogAnimator=function(_DialogAnimator2){function IOSDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"ease-in-out":_ref3$timing,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.3:_ref3$duration;_classCallCheck(this,IOSDialogAnimator),_get(Object.getPrototypeOf(IOSDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(IOSDialogAnimator,_DialogAnimator2),_createClass(IOSDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSDialogAnimator}(DialogAnimator),SlideDialogAnimator=function(_DialogAnimator3){function SlideDialogAnimator(){var _ref4=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref4$timing=_ref4.timing,timing=void 0===_ref4$timing?"cubic-bezier(.1, .7, .4, 1)":_ref4$timing,_ref4$delay=_ref4.delay,delay=void 0===_ref4$delay?0:_ref4$delay,_ref4$duration=_ref4.duration,duration=void 0===_ref4$duration?.2:_ref4$duration;_classCallCheck(this,SlideDialogAnimator),_get(Object.getPrototypeOf(SlideDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(SlideDialogAnimator,_DialogAnimator3),_createClass(SlideDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),SlideDialogAnimator}(DialogAnimator);ons._internal=ons._internal||{},ons._internal.DialogAnimator=DialogAnimator,ons._internal.AndroidDialogAnimator=AndroidDialogAnimator,ons._internal.IOSDialogAnimator=IOSDialogAnimator,ons._internal.SlideDialogAnimator=SlideDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=function(_ModalAnimator){function FadeModalAnimator(options){_classCallCheck(this,FadeModalAnimator),options.timing=options.timing||"linear",options.duration=options.duration||"0.3",options.delay=options.delay||0,_get(Object.getPrototypeOf(FadeModalAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeModalAnimator,_ModalAnimator),_createClass(FadeModalAnimator,[{key:"show",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}},{key:"hide",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}}]),FadeModalAnimator}(ModalAnimator);ons._internal=ons._internal||{},ons._internal.FadeModalAnimator=FadeModalAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function FadeNavigatorTransitionAnimator(options){_classCallCheck(this,FadeNavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),_get(Object.getPrototypeOf(FadeNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(FadeNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.element._getContentElement(),enterPage.element._getBackgroundElement()]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}),animit(enterPage.element._getToolbarElement()).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle())}},{key:"pop",value:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.element._getContentElement(),leavePage.element._getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}),animit(leavePage.element._getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))}}]),FadeNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.FadeNavigatorTransitionAnimator=FadeNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=function(_PopoverAnimator){function FadePopoverAnimator(options){_classCallCheck(this,FadePopoverAnimator),_get(Object.getPrototypeOf(FadePopoverAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadePopoverAnimator,_PopoverAnimator),_createClass(FadePopoverAnimator,[{key:"show",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).wait(this.delay).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),FadePopoverAnimator}(PopoverAnimator);ons._internal=ons._internal||{},ons._internal.FadePopoverAnimator=FadePopoverAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function IOSSlideNavigatorTransitionAnimator(options){_classCallCheck(this,IOSSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(IOSSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black; opacity: 0;"></div>\n ')}return _inherits(IOSSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(IOSSlideNavigatorTransitionAnimator,[{key:"_decompose",value:function(page){CustomElements.upgrade(page.element);var toolbar=page.element._getToolbarElement();CustomElements.upgrade(toolbar);var left=toolbar._getToolbarLeftItemsElement(),right=toolbar._getToolbarRightItemsElement(),excludeBackButtonLabel=function(elements){for(var result=[],i=0;i<elements.length;i++)if("ons-back-button"===elements[i].nodeName.toLowerCase()){var iconElement=elements[i].querySelector(".ons-back-button__icon");iconElement&&result.push(iconElement)}else result.push(elements[i]);return result},other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[toolbar._getToolbarCenterItemsElement(),toolbar._getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.element._getContentElement(),background:page.element._getBackgroundElement(),toolbar:toolbar,bottomToolbar:page.element._getBottomToolbarElement()}}},{key:"_shouldAnimateToolbar",value:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.element._canAnimateToolbar()&&leavePage.element._canAnimateToolbar(),noAndroidLikeToolbar=!enterPage.element._getToolbarElement().classList.contains("navigation-bar--android")&&!leavePage.element._getToolbarElement().classList.contains("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar}},{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:.1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(this.delay+.3).restoreStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()}),animit(leavePageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePageDecomposition.other).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle())):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()})))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(0).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()})))}}]),IOSSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.IOSSlideNavigatorTransitionAnimator=IOSSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,LazyRepeatDelegate=function(){function LazyRepeatDelegate(){_classCallCheck(this,LazyRepeatDelegate)}return _createClass(LazyRepeatDelegate,[{key:"prepareItem",value:function(index,done){throw new Error("This is an abstract method.")}},{key:"countItems",value:function(){throw new Error("This is an abstract method.")}},{key:"updateItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"calculateItemHeight",value:function(index){throw new Error("This is an abstract method.")}},{key:"destroyItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"destroy",value:function(){throw new Error("This is an abstract method.")}}]),LazyRepeatDelegate}(),LazyRepeatProvider=function(){function LazyRepeatProvider(wrapperElement,templateElement,delegate){if(_classCallCheck(this,LazyRepeatProvider),!(delegate instanceof LazyRepeatDelegate))throw new Error('"delegate" parameter must be an instance of ons._internal.LazyRepeatDelegate.');if(!(templateElement instanceof Element))throw new Error('"templateElement" parameter must be an instance of Element.');if(!(wrapperElement instanceof Element))throw new Error('"wrapperElement" parameter must be an instance of Element.');if(this._templateElement=templateElement,this._wrapperElement=wrapperElement,this._delegate=delegate,this._pageContent=util.findParent(wrapperElement,".page__content"),this._pageContent||(this._pageContent=util.findParent(wrapperElement,".ons-scroller__content")),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> or an <ons-scroller> element.");this._itemHeightSum=[],this._maxIndex=0,this._renderedItems={},this._addEventListeners(),this._onChange()}return _createClass(LazyRepeatProvider,[{key:"_countItems",value:function(){return this._delegate.countItems()}},{key:"_getItemHeight",value:function(i){return this._delegate.calculateItemHeight(i)}},{key:"_getTopOffset",value:function(){return"undefined"!=typeof this._wrapperElement&&null!==this._wrapperElement?this._wrapperElement.getBoundingClientRect().top:0}},{key:"_onChange",value:function(){this._render()}},{key:"_render",value:function(){for(var items=this._getItemsInView(),keep={},i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key);this._wrapperElement.style.height=this._calculateListHeight()+"px"}},{key:"_calculateListHeight",value:function(){var indices=Object.keys(this._renderedItems).map(function(n){return parseInt(n)});return this._itemHeightSum[indices.pop()]||0}},{key:"_isRendered",value:function(index){return this._renderedItems.hasOwnProperty(index)}},{key:"_renderElement",
value:function(_ref){var _this=this,index=_ref.index,top=_ref.top;if(this._isRendered(index)){var currentItem=this._renderedItems[index];this._delegate.updateItem(index,currentItem);var element=this._renderedItems[index].element;return void(element.style.top=this._wrapperElement.offsetTop+top+"px")}this._delegate.prepareItem(index,function(item){var element=item.element;element.style.position="absolute",element.style.top=top+"px",element.style.left="0px",element.style.right="0px",_this._wrapperElement.appendChild(element),_this._renderedItems[index]=item})}},{key:"_removeElement",value:function(index){if(this._isRendered(index)){var item=this._renderedItems[index];this._delegate.destroyItem(index,item),item.element.parentElement&&item.element.parentElement.removeChild(item.element),item=null,delete this._renderedItems[index]}}},{key:"_removeAllElements",value:function(){for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&this._removeElement(key)}},{key:"_calculateStartIndex",value:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}}},{key:"_recalculateItemHeightSum",value:function(){for(var sums=this._itemHeightSum,i=0,sum=0;i<Math.min(sums.length,this._countItems());i++)sum+=this._getItemHeight(i),sums[i]=sum}},{key:"_getItemsInView",value:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems();cnt!==this._itemCount&&(this._recalculateItemHeightSum(),this._maxIndex=cnt-1),this._itemCount=cnt;var startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight(i);i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),i>0?this._itemHeightSum[i]=this._itemHeightSum[i-1]+h:this._itemHeightSum[i]=h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items}},{key:"_debounce",value:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}}},{key:"_doubleFireOnTouchend",value:function(){this._render(),this._debounce(this._render.bind(this),100)}},{key:"_addEventListeners",value:function(){ons.platform.isIOS()?this._boundOnChange=this._debounce(this._onChange.bind(this),30):this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.addEventListener("touchmove",this._boundOnChange,!0),this._pageContent.addEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.addEventListener("resize",this._boundOnChange,!0)}},{key:"_removeEventListeners",value:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.removeEventListener("touchmove",this._boundOnChange,!0),this._pageContent.removeEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.removeEventListener("resize",this._boundOnChange,!0)}},{key:"destroy",value:function(){this._delegate.destroy(),this._parentElement=this._templateElement=this._delegate=this._renderedItems=null,this._removeEventListeners()}}]),LazyRepeatProvider}();ons._internal=ons._internal||{},ons._internal.LazyRepeatProvider=LazyRepeatProvider,ons._internal.LazyRepeatDelegate=LazyRepeatDelegate}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function LiftNavigatorTransitionAnimator(options){_classCallCheck(this,LiftNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(LiftNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black;"></div>\n ')}return _inherits(LiftNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(LiftNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element);var maskClear=animit(this.backgroundMask).wait(.6).queue(function(done){_this.backgroundMask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).wait(.2).restoreStyle().queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:this.duration,timing:this.timing}))}},{key:"pop",value:function(enterPage,leavePage,callback){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element),animit.runAll(animit(this.backgroundMask).wait(.4).queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:this.duration,timing:this.timing}))}}]),LiftNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.LiftNavigatorTransitionAnimator=LiftNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModifierUtil=function(){function ModifierUtil(){_classCallCheck(this,ModifierUtil)}return _createClass(ModifierUtil,null,[{key:"diff",value:function(last,current){function makeDict(modifier){var dict={};return ModifierUtil.split(modifier).forEach(function(token){return dict[token]=token}),dict}last=makeDict((""+last).trim()),current=makeDict((""+current).trim());var removed=Object.keys(last).reduce(function(result,token){return current[token]||result.push(token),result},[]),added=Object.keys(current).reduce(function(result,token){return last[token]||result.push(token),result},[]);return{added:added,removed:removed}}},{key:"applyDiffToClassList",value:function(diff,classList,template){diff.added.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.add(klass)}),diff.removed.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.remove(klass)})}},{key:"applyDiffToElement",value:function(diff,element,scheme){for(var selector in scheme)if(scheme.hasOwnProperty(selector))for(var targetElements=""===selector?[element]:element.querySelectorAll(selector),i=0;i<targetElements.length;i++)ModifierUtil.applyDiffToClassList(diff,targetElements[i].classList,scheme[selector])}},{key:"onModifierChanged",value:function(last,current,element,scheme){return ModifierUtil.applyDiffToElement(ModifierUtil.diff(last,current),element,scheme)}},{key:"initModifier",value:function(element,scheme){var modifier=element.getAttribute("modifier");"string"==typeof modifier&&ModifierUtil.applyDiffToElement({removed:[],added:ModifierUtil.split(modifier)},element,scheme)}},{key:"split",value:function(modifier){return"string"!=typeof modifier?[]:modifier.trim().split(/ +/).filter(function(token){return""!==token})}}]),ModifierUtil}();ons._internal=ons._internal||{},ons._internal.ModifierUtil=ModifierUtil}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,NavigatorPage=function(){function NavigatorPage(params){var _this=this;_classCallCheck(this,NavigatorPage),this.page=params.page,this.name=params.page,this.element=params.element,this.options=params.options,this.navigator=params.navigator,this.initialContent=params.initialContent,this._blockEvents=function(event){(_this.navigator._isPopping||_this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())},this._pointerEvents.forEach(function(event){return _this.element.addEventListener(event,_this._blockEvents)},!1)}return _createClass(NavigatorPage,[{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"getPageView",value:function(){if(!this._page&&(this._page=util.findParent("ons-page"),!this._page))throw new Error("Fail to fetch ons-page element.");return this._page}},{key:"destroy",value:function(){var _this2=this;this._pointerEvents.forEach(function(event){return _this2.element.removeEventListener(event,_this2._blockEvents)},!1),this.element._destroy();var index=this.navigator._pages.indexOf(this);-1!==index&&this.navigator._pages.splice(index,1),this.element=this._page=this.options=this.navigator=null}},{key:"_pointerEvents",get:function(){return["touchmove"]}}]),NavigatorPage}();window.ons._internal.NavigatorPage=NavigatorPage}(window.ons=window.ons||{}),function(ons){"use strict";ons._internal=ons._internal||{},ons._internal.nullElement=document.createElement("div"),ons._internal.isEnabledAutoStatusBarFill=function(){return!!ons._config.autoStatusBarFill},ons._internal.normalizePageHTML=function(html){return html=(""+html).trim(),html.match(/^<ons-page/)||(html="<ons-page _muted>"+html+"</ons-page>"),html},ons._internal.waitDOMContentLoaded=function(callback){"loading"===document.readyState||"uninitialized"==document.readyState?window.document.addEventListener("DOMContentLoaded",callback):setImmediate(callback)},ons._internal.shouldFillStatusBar=function(element){if(ons._internal.isEnabledAutoStatusBarFill()&&ons.platform.isWebView()&&ons.platform.isIOS7above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,!element||!element.hasAttribute)return!0}}return!1},ons._internal.templateStore={_storage:{},get:function(key){return ons._internal.templateStore._storage[key]||null},set:function(key,template){ons._internal.templateStore._storage[key]=template}},document.addEventListener("_templateloaded",function(e){"ons-template"===e.target.nodeName.toLowerCase()&&ons._internal.templateStore.set(e.templateId,e.template)},!1),document.addEventListener("DOMContentLoaded",function(){function register(query){for(var templates=document.querySelectorAll(query),i=0;i<templates.length;i++)ons._internal.templateStore.set(templates[i].getAttribute("id"),templates[i].textContent)}register('script[type="text/ons-template"]'),register('script[type="text/template"]'),register('script[type="text/ng-template"]')},!1),ons._internal.getTemplateHTMLAsync=function(page){return new Promise(function(resolve,reject){setImmediate(function(){var cache=ons._internal.templateStore.get(page);if(cache){var html="string"==typeof cache?cache:cache[1];resolve(html)}else!function(){var xhr=new XMLHttpRequest;xhr.open("GET",page,!0),xhr.onload=function(response){var html=xhr.responseText;xhr.status>=400&&xhr.status<600?reject(html):resolve(html)},xhr.onerror=function(){throw new Error("The page is not found: "+page)},xhr.send(null)}()})})},ons._internal.getPageHTMLAsync=function(page){var pages=ons.pageAttributeExpression.evaluate(page),getPage=function getPage(page){return"string"!=typeof page?Promise.reject("Must specify a page."):ons._internal.getTemplateHTMLAsync(page).then(function(html){return ons._internal.normalizePageHTML(html)},function(error){return 0===pages.length?Promise.reject(error):getPage(pages.shift())}).then(function(html){return ons._internal.normalizePageHTML(html)})};return getPage(pages.shift())}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util;ons.notification={},ons.notification._createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,_callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder,defaultValue,submitOnEnter,compile){compile=compile||function(object){return object};var titleElementHTML="string"==typeof title?'<div class="alert-dialog-title"></div>':"",dialogElement=util.createElement("\n <ons-alert-dialog>\n "+titleElementHTML+'\n <div class="alert-dialog-content"></div>\n <div class="alert-dialog-footer"></div>\n </ons-alert-dialog>'),titleElement=dialogElement.querySelector(".alert-dialog-title"),messageElement=dialogElement.querySelector(".alert-dialog-content"),footerElement=dialogElement.querySelector(".alert-dialog-footer"),inputElement=void 0;"string"==typeof title&&(titleElement.textContent=title),titleElement=null,dialogElement.setAttribute("animation",animation),messageIsHTML?messageElement.innerHTML=message:messageElement.textContent=message,promptDialog&&(inputElement=util.createElement('<input class="text-input" type="text"></input>'),modifier&&inputElement.classList.add("text-input--"+modifier),inputElement.setAttribute("placeholder",placeholder),inputElement.value=defaultValue,inputElement.style.width="100%",inputElement.style.marginTop="10px",messageElement.appendChild(inputElement),submitOnEnter&&inputElement.addEventListener("keypress",function(event){13===event.keyCode&&dialogElement.hide({callback:function(){_callback(inputElement.value),dialogElement.destroy(),dialogElement=null}})},!1)),document.body.appendChild(dialogElement),compile(dialogElement),buttonLabels.length<=2&&footerElement.classList.add("alert-dialog-footer--one");for(var createButton=function(i){var buttonElement=util.createElement('<button class="alert-dialog-button"></button>');buttonElement.textContent=buttonLabels[i],i==primaryButtonIndex&&buttonElement.classList.add("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonElement.classList.add("alert-dialog-button--one");var onClick=function onClick(){buttonElement.removeEventListener("click",onClick,!1),dialogElement.hide({callback:function(){_callback(promptDialog?inputElement.value:i),dialogElement.destroy(),dialogElement=inputElement=buttonElement=null}})};buttonElement.addEventListener("click",onClick,!1),footerElement.appendChild(buttonElement)},i=0;i<buttonLabels.length;i++)createButton(i);return cancelable&&(dialogElement.setCancelable(cancelable),dialogElement.addEventListener("cancel",function(){_callback(promptDialog?null:-1),setTimeout(function(){dialogElement.destroy(),dialogElement=null,inputElement=null})},!1)),dialogElement.show({callback:function(){inputElement&&promptDialog&&autofocus&&inputElement.focus()}}),messageElement=footerElement=null,modifier&&dialogElement.setAttribute("modifier",modifier),Promise.resolve(dialogElement)},ons.notification._alertOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1,"","",!1,options.compile)},ons.notification.alert=ons.notification._alertOriginal,ons.notification._confirmOriginal=function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1,"","",!1,options.compile)},ons.notification.confirm=ons.notification._confirmOriginal,ons.notification._promptOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",defaultValue:"",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0,submitOnEnter:!0};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder,options.defaultValue,options.submitOnEnter,options.compile)},ons.notification.prompt=ons.notification._promptOriginal}(window.ons=window.ons||{}),function(ons){var create=function(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;"orientation"in window?window.orientation%180===0?this._isPortrait=function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var _this=this,isPortrait=this._isPortrait(),nIter=0,interval=setInterval(function(){nIter++;var w=window.innerWidth,h=window.innerHeight;isPortrait&&h>=w||!isPortrait&&w>=h?(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval)):50===nIter&&(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval))},20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj};ons.orientation=create()._init()}(window.ons=window.ons||{}),function(ons){ons.pageAttributeExpression={_variables:{},defineVariable:function(name,value){var overwrite=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];if("string"!=typeof name)throw new Error("Variable name must be a string.");if("string"!=typeof value&&"function"!=typeof value)throw new Error("Variable value must be a string or a function.");if(this._variables.hasOwnProperty(name)&&!overwrite)throw new Error('"'+name+'" is already defined.');this._variables[name]=value},getVariable:function(name){return this._variables.hasOwnProperty(name)?this._variables[name]:null},removeVariable:function(name){delete this._variables[name]},getAllVariables:function(){return this._variables},_parsePart:function(part){var c=void 0,inInterpolation=!1,currentIndex=0,tokens=[];if(0===part.length)throw new Error("Unable to parse empty string.");for(var i=0;i<part.length;i++)if(c=part.charAt(i),"$"===c&&"{"===part.charAt(i+1)){if(inInterpolation)throw new Error("Nested interpolation not supported.");var token=part.substring(currentIndex,i);token.length>0&&tokens.push(part.substring(currentIndex,i)),currentIndex=i,inInterpolation=!0}else if("}"===c){if(!inInterpolation)throw new Error("} must be preceeded by ${");var token=part.substring(currentIndex,i+1);token.length>0&&tokens.push(part.substring(currentIndex,i+1)),currentIndex=i+1,inInterpolation=!1}if(inInterpolation)throw new Error("Unterminated interpolation.");return tokens.push(part.substring(currentIndex,part.length)),tokens},_replaceToken:function(token){var re=/^\${(.*?)}$/,match=token.match(re);if(match){var _name=match[1].trim(),variable=this.getVariable(_name);if(null===variable)throw new Error('Variable "'+_name+'" does not exist.');if("string"==typeof variable)return variable;var rv=variable();if("string"!=typeof rv)throw new Error("Must return a string.");return rv}return token},_replaceTokens:function(tokens){return tokens.map(this._replaceToken.bind(this))},_parseExpression:function(expression){return expression.split(",").map(function(part){return part.trim()}).map(this._parsePart.bind(this)).map(this._replaceTokens.bind(this)).map(function(part){return part.join("")})},evaluate:function(expression){return expression?this._parseExpression(expression):[]}},ons.pageAttributeExpression.defineVariable("mobileOS",ons.platform.getMobileOS()),ons.pageAttributeExpression.defineVariable("iOSDevice",ons.platform.getIOSDevice()),ons.pageAttributeExpression.defineVariable("runtime",function(){return ons.platform.isWebView()?"cordova":"browser"})}(window.ons=window.ons||{}),function(ons){"use strict";ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function SimpleSlideNavigatorTransitionAnimator(options){_classCallCheck(this,SimpleSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.3,timing:"cubic-bezier(.1, .7, .4, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(SimpleSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%; z-index: 2;\n background-color: black; opacity: 0;"></div>\n '),this.blackMaskOpacity=.4}return _inherits(SimpleSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(SimpleSlideNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentElement.insertBefore(this.backgroundMask,leavePage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().wait(.2).queue(function(done){callback(),done()}))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}}]),SimpleSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.SimpleSlideNavigatorTransitionAnimator=SimpleSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var TabbarAnimator=function(){function TabbarAnimator(options){_classCallCheck(this,TabbarAnimator),options=options||{},this.timing=options.timing||"linear",this.duration=void 0!==options.duration?options.duration:"0.4",this.delay=void 0!==options.delay?options.delay:"0"}return _createClass(TabbarAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){throw new Error("This method must be implemented.")}}]),TabbarAnimator}(),TabbarNoneAnimator=function(_TabbarAnimator){function TabbarNoneAnimator(){_classCallCheck(this,TabbarNoneAnimator),_get(Object.getPrototypeOf(TabbarNoneAnimator.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarNoneAnimator,_TabbarAnimator),_createClass(TabbarNoneAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){done()}}]),TabbarNoneAnimator}(TabbarAnimator),TabbarFadeAnimator=function(_TabbarAnimator2){function TabbarFadeAnimator(options){_classCallCheck(this,TabbarFadeAnimator),options.timing=void 0!==options.timing?options.timing:"linear",options.duration=void 0!==options.duration?options.duration:"0.4",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarFadeAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarFadeAnimator,_TabbarAnimator2),_createClass(TabbarFadeAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D(0, 0, 0)",opacity:0}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)",opacity:1}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:this.duration,timing:this.timing}))}}]),TabbarFadeAnimator}(TabbarAnimator),TabbarSlideAnimator=function(_TabbarAnimator3){function TabbarSlideAnimator(options){_classCallCheck(this,TabbarSlideAnimator),options.timing=void 0!==options.timing?options.timing:"ease-in",options.duration=void 0!==options.duration?options.duration:"0.15",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarSlideAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarSlideAnimator,_TabbarAnimator3),
_createClass(TabbarSlideAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){var sgn=enterIndex>leaveIndex;animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D("+(sgn?"":"-")+"100%, 0, 0)"}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)"},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)"}).wait(this.delay).queue({transform:"translate3D("+(sgn?"-":"")+"100%, 0, 0)"},{duration:this.duration,timing:this.timing}))}}]),TabbarSlideAnimator}(TabbarAnimator);ons._internal=ons._internal||{},ons._internal.TabbarAnimator=TabbarAnimator,ons._internal.TabbarFadeAnimator=TabbarFadeAnimator,ons._internal.TabbarNoneAnimator=TabbarNoneAnimator,ons._internal.TabbarSlideAnimator=TabbarSlideAnimator}(window.ons=window.ons||{}),function(window){"use strict";function setup(){GestureDetector.READY||(Event.determineEventTypes(),Utils.each(GestureDetector.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(GestureDetector.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(GestureDetector.DOCUMENT,EVENT_END,Detection.detect),GestureDetector.READY=!0)}var GestureDetector=function GestureDetector(element,options){return new GestureDetector.Instance(element,options||{})};GestureDetector.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},GestureDetector.DOCUMENT=document,GestureDetector.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,GestureDetector.HAS_TOUCHEVENTS="ontouchstart"in window,GestureDetector.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),GestureDetector.NO_MOUSEEVENTS=GestureDetector.HAS_TOUCHEVENTS&&GestureDetector.IS_MOBILE||GestureDetector.HAS_POINTEREVENTS,GestureDetector.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=GestureDetector.DIRECTION_DOWN="down",DIRECTION_LEFT=GestureDetector.DIRECTION_LEFT="left",DIRECTION_UP=GestureDetector.DIRECTION_UP="up",DIRECTION_RIGHT=GestureDetector.DIRECTION_RIGHT="right",POINTER_MOUSE=GestureDetector.POINTER_MOUSE="mouse",POINTER_TOUCH=GestureDetector.POINTER_TOUCH="touch",POINTER_PEN=GestureDetector.POINTER_PEN="pen",EVENT_START=GestureDetector.EVENT_START="start",EVENT_MOVE=GestureDetector.EVENT_MOVE="move",EVENT_END=GestureDetector.EVENT_END="end",EVENT_RELEASE=GestureDetector.EVENT_RELEASE="release",EVENT_TOUCH=GestureDetector.EVENT_TOUCH="touch";GestureDetector.READY=!1,GestureDetector.plugins=GestureDetector.plugins||{},GestureDetector.gestures=GestureDetector.gestures||{};var Utils=GestureDetector.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||void 0!==dest[key]&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(void 0!==obj.length){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null===toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=GestureDetector.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=GestureDetector.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=GestureDetector.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:GestureDetector.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(GestureDetector.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=GestureDetector.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=GestureDetector.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>GestureDetector.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return void 0===options[gesture.name]&&(options[gesture.name]=!0),Utils.extend(GestureDetector.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};GestureDetector.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},GestureDetector.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},GestureDetector.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=GestureDetector.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(Utils.isVertical(lastDirection)?ev.direction=ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.direction=ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;GestureDetector.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),GestureDetector.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&¤t.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;GestureDetector.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),GestureDetector.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},GestureDetector.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return;(ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;GestureDetector.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),GestureDetector.gestures.Touch={name:"touch",index:-(1/0),defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?void ev.stopDetect():(inst.options.preventDefault&&ev.preventDefault(),void(ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev)))}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;GestureDetector.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),window.ons=window.ons||{},window.ons.GestureDetector=GestureDetector}(window),window.styler=function(){"use strict";var styler=function(element,style){return styler.css.apply(styler,arguments)};return styler.css=function(element,styles){var keys=Object.keys(styles);return keys.forEach(function(key){key in element.style?element.style[key]=styles[key]:styler._prefix(key)in element.style?element.style[styler._prefix(key)]=styles[key]:console.warn("No such style property: "+key)}),element},styler._prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),prefix=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return function(name){return prefix+name.substr(0,1).toUpperCase()+name.substr(1)}}(),styler.clear=function(element){styler._clear(element)},styler._clear=function(element){for(var len=element.style.length,style=element.style,keys=[],i=0;len>i;i++)keys.push(style[i]);keys.forEach(function(key){style[key]=""})},styler}(),function(ons){window.addEventListener("load",function(){return FastClick.attach(document.body)},!1),window.addEventListener("DOMContentLoaded",function(){ons._defaultDeviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(window.document.body,function(){navigator.app.exitApp()})},!1),ons.ready(function(){ons._setupLoadingPlaceHolders()}),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem,rule){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),"function"!=typeof HTMLElement?(ons._BaseElement=function(){},ons._BaseElement.prototype=document.createElement("div")):ons._BaseElement=HTMLElement,"undefined"!=typeof module&&module.exports&&(module.exports=ons)}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x11,_x12,_x13){for(var _again=!0;_again;){var object=_x11,property=_x12,receiver=_x13;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x11=parent,_x12=property,_x13=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,SplitterElement=function(_ons$_BaseElement){function SplitterElement(){_classCallCheck(this,SplitterElement),_get(Object.getPrototypeOf(SplitterElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterElement,_ons$_BaseElement),_createClass(SplitterElement,[{key:"createdCallback",value:function(){this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._boundOnModeChange=this._onModeChange.bind(this)}},{key:"_onModeChange",value:function(event){event.target.parentElement===this&&this._layout()}},{key:"_getSideElement",value:function(side){var result=util.findChild(this,function(element){return"ons-splitter-side"===element.nodeName.toLowerCase()&&element.getAttribute("side")===side});return result&&CustomElements.upgrade(result),result}},{key:"_layout",value:function(){var content=this._getContentElement(),left=this._getSideElement("left"),right=this._getSideElement("right");content&&(left&&left.getCurrentMode&&"split"===left.getCurrentMode()?content.style.left=left._getWidth():content.style.left="0px",right&&right.getCurrentMode&&"split"===right.getCurrentMode()?content.style.right=right._getWidth():content.style.right="0px")}},{key:"_getContentElement",value:function(){return util.findChild(this,"ons-splitter-content")}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"openRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("right",options)}},{key:"_getMaskElement",value:function(){var mask=util.findChild(this,"ons-splitter-mask");return mask||this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"openLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("left",options)}},{key:"_open",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.open(options):!1}},{key:"closeRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("right",options)}},{key:"closeLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("left",options)}},{key:"_close",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.close(options):!1}},{key:"toggleLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("left",options)}},{key:"toggleRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("right",options)}},{key:"_toggle",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.toggle(options):!1}},{key:"leftIsOpened",value:function(){return this._isOpened("left")}},{key:"rightIsOpened",value:function(){return this._isOpened("right")}},{key:"_isOpened",value:function(side){var menu=this._getSideElement(side);return menu?menu.isOpened():!1}},{key:"loadContentPage",value:function(page){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],content=this._getContentElement();if(content)return content.load(page,options);throw new Error('child "ons-splitter-content" element is not found in this element.')}},{key:"_onDeviceBackButton",value:function(handler){var left=this._getSideElement("left"),right=this._getSideElement("right");return left.isOpened()?void left.close():right.isOpened()?void right.close():void handler.callParentHandler()}},{key:"attachedCallback",value:function(){var _this=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),this._assertChildren(),this.addEventListener("modechange",this._boundOnModeChange,!1),setImmediate(function(){return _this._layout()})}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_assertChildren",value:function(){var names=["ons-splitter-content","ons-splitter-side","ons-splitter-mask"],contentCount=0,sideCount=0,maskCount=0;if(util.arrayFrom(this.children).forEach(function(element){var name=element.nodeName.toLowerCase();if(-1===names.indexOf(name))throw new Error('"'+name+'" element is not allowed in "ons-splitter" element.');"ons-splitter-content"===name?contentCount++:"ons-splitter-content"===name?sideCount++:"ons-splitter-mask"===name&&maskCount++}),contentCount>1)throw new Error("too many <ons-splitter-content> elements.");if(sideCount>2)throw new Error("too many <ons-splitter-side> elements.");if(maskCount>1)throw new Error("too many <ons-splitter-mask> elements.");0===maskCount&&this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this.removeEventListener("modechange",this._boundOnModeChange,!1)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}}]),SplitterElement}(ons._BaseElement);window.OnsSplitterElement||(window.OnsSplitterElement=document.registerElement("ons-splitter",{prototype:SplitterElement.prototype}),window.OnsSplitterElement._animatorDict={"default":ons._internal.OverlaySplitterAnimator,overlay:ons._internal.OverlaySplitterAnimator},window.OnsSplitterElement.registerAnimator=function(name,Animator){if(!(Animator instanceof ons._internal.SplitterAnimator))throw new Error("Animator parameter must be an instance of SplitterAnimator.");window.OnsSplitterElement._animatorDict[name]=Animator},window.OnsSplitterElement.SplitterAnimator=ons._internal.SplitterAnimator)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"tab-bar--*__item",".tab-bar__button":"tab-bar--*__button"},ModifierUtil=ons._internal.ModifierUtil,util=ons._util,templateSource=util.createElement('\n <div>\n <input type="radio" style="display: none">\n <button class="tab-bar__button tab-bar-inner"></button>\n </div>\n '),defaultInnerTemplateSource=util.createElement('\n <div>\n <div class="tab-bar__icon">\n <ons-icon icon="ion-cloud" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon>\n </div>\n <div class="tab-bar__label">label</div>\n </div>\n '),TabElement=function(_ons$_BaseElement){function TabElement(){_classCallCheck(this,TabElement),_get(Object.getPrototypeOf(TabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabElement,_ons$_BaseElement),_createClass(TabElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){for(var fragment=document.createDocumentFragment(),hasChildren=!1;this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),fragment.appendChild(node),node.nodeType==Node.ELEMENT_NODE&&(hasChildren=!0)}for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this.classList.add("tab-bar__item");var button=util.findChild(this,".tab-bar__button");hasChildren?(button.appendChild(fragment),this._hasDefaultTemplate=!1):(this._hasDefaultTemplate=!0,this._updateDefaultTemplate())}},{key:"_updateDefaultTemplate",value:function(){
function getLabelElement(){return self.querySelector(".tab-bar__label")}function getIconElement(){return self.querySelector("ons-icon")}if(this._hasDefaultTemplate){for(var button=util.findChild(this,".tab-bar__button"),template=defaultInnerTemplateSource.cloneNode(!0);template.children[0];)button.appendChild(template.children[0]);var self=this,icon=this.getAttribute("icon"),label=this.getAttribute("label");if("string"==typeof icon)getIconElement().setAttribute("icon",icon);else{var wrapper=button.querySelector(".tab-bar__icon");wrapper.parentNode.removeChild(wrapper)}"string"==typeof label?getLabelElement().textContent=label:getLabelElement().parentNode.removeChild(getLabelElement())}}},{key:"_onClick",value:function(){var tabbar=this._findTabbarElement();tabbar&&tabbar.setActiveTab(this._findTabIndex())}},{key:"isPersistent",value:function(){return this.hasAttribute("persistent")}},{key:"setActive",value:function(){var radio=util.findChild(this,"input");radio.checked=!0,this.classList.add("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="none"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="inherit"})}},{key:"setInactive",value:function(){var radio=util.findChild(this,"input");radio.checked=!1,this.classList.remove("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="inherit"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="none"})}},{key:"isLoaded",value:function(){return!1}},{key:"_loadPageElement",value:function(callback,link){var _this=this;this.isPersistent()?this._pageElement?callback(this._pageElement):this._createPageElement(this.getAttribute("page"),function(element){link(element,function(element){_this._pageElement=element,callback(element)})}):(this._pageElement=null,this._createPageElement(this.getAttribute("page"),callback))}},{key:"_createPageElement",value:function(page,callback){ons._internal.getPageHTMLAsync(page).then(function(html){callback(util.createElement(html.trim()))})}},{key:"isActive",value:function(){return this.classList.contains("active")}},{key:"canReload",value:function(){return!this.hasAttribute("no-reload")}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"attachedCallback",value:function(){var _this2=this;this._ensureElementPosition(),this.hasAttribute("active")&&!function(){var tabbar=_this2._findTabbarElement(),tabIndex=_this2._findTabIndex();window.OnsTabbarElement.rewritables.ready(tabbar,function(){setImmediate(function(){return tabbar.setActiveTab(tabIndex,{animation:"none"})})})}(),this.addEventListener("click",this._boundOnClick,!1)}},{key:"_findTabbarElement",value:function(){return this.parentNode&&"ons-tabbar"===this.parentNode.nodeName.toLowerCase()?this.parentNode:this.parentNode.parentNode&&"ons-tabbar"===this.parentNode.parentNode.nodeName.toLowerCase()?this.parentNode.parentNode:null}},{key:"_findTabIndex",value:function(){for(var elements=this.parentNode.children,i=0;i<elements.length;i++)if(this===elements[i])return i}},{key:"_ensureElementPosition",value:function(){if(!this._findTabbarElement())throw new Error("This ons-tab element is must be child of ons-tabbar element.")}},{key:"attributeChangedCallback",value:function(name,last,current){return this._hasDefaultTemplate&&("icon"===name||"label"===name)&&this._updateDefaultTemplate(),"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabElement}(ons._BaseElement);window.OnsTabElement||(window.OnsTabElement=document.registerElement("ons-tab",{prototype:TabElement.prototype}),document.registerElement("ons-tabbar-item",{prototype:Object.create(TabElement.prototype)}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={"":"alert-dialog--*",".alert-dialog-title":"alert-dialog-title--*",".alert-dialog-content":"alert-dialog-content--*",".alert-dialog-footer":"alert-dialog-footer--*",".alert-dialog-button":"alert-dialog-button--*",".alert-dialog-footer--one":"alert-dialog-footer--one--*",".alert-dialog-button--one":"alert-dialog-button--one--*",".alert-dialog-button--primal":"alert-dialog-button--primal--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidAlertDialogAnimator=ons._internal.AndroidAlertDialogAnimator,IOSAlertDialogAnimator=ons._internal.IOSAlertDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,AlertDialogAnimator=ons._internal.AlertDialogAnimator,_animatorDict={"default":ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,fade:ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,slide:SlideDialogAnimator,none:AlertDialogAnimator},AlertDialogElement=function(_ons$_BaseElement){function AlertDialogElement(){_classCallCheck(this,AlertDialogElement),_get(Object.getPrototypeOf(AlertDialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(AlertDialogElement,_ons$_BaseElement),_createClass(AlertDialogElement,[{key:"createdCallback",value:function(){this._compile(),this._mask=this._createMask(this.getAttribute("mask-color")),ModifierUtil.initModifier(this,scheme),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:AlertDialogAnimator,baseClassName:"AlertDialogAnimator",defaultAnimation:this.getAttribute("animation")}),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this)}},{key:"_compile",value:function(){if(this.style.display="none",this.style.zIndex="20001",this.classList.add("alert-dialog"),ons.platform.isAndroid()){var modifier=this.hasAttribute("modifier")?this.getAttribute("modifier"):"";this.setAttribute("modifier",(modifier+" android").trim())}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),util.triggerElementEvent(this,"preshow",{alertDialog:this,cancel:function(){_cancel2=!0}}),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock();_this._mask.style.display="block",_this._mask.style.opacity=1,_this.style.display="block";var animator=_this._animatorFactory.newAnimator(options);animator.show(_this,function(){_this._visible=!0,unlock(),util.triggerElementEvent(_this,"postshow",{alertDialog:_this}),callback()})})}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{alertDialog:this,cancel:function(){_cancel3=!0}}),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",_this2._mask.style.display="none",_this2._visible=!1,unlock(),util.triggerElementEvent(_this2,"posthide",{alertDialog:_this2}),callback()})})}},{key:"isShown",value:function(){return this._visible}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this),this._mask.parentElement&&this._mask.parentElement.removeChild(this._mask)}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this3=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this3,"cancel")}})}},{key:"_createMask",value:function(color){return this._mask=util.createElement("<div></div>"),this._mask.classList.add("alert-dialog-mask"),this._mask.style.zIndex=2e4,this._mask.style.display="none",color&&(this._mask.style.backgroundColor=color),document.body.appendChild(this._mask),this._mask}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_titleElement",get:function(){return util.findChild(this,".alert-dialog-title")}},{key:"_contentElement",get:function(){return util.findChild(this,".alert-dialog-content")}},{key:"_dialog",get:function(){return this}}]),AlertDialogElement}(ons._BaseElement);window.OnsAlertDialogElement||(window.OnsAlertDialogElement=document.registerElement("ons-alert-dialog",{prototype:AlertDialogElement.prototype}),window.OnsAlertDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof AlertDialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,iOSTemplateElement=util.createElement('\n <span\n class="toolbar-button--quiet"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n\n <i class="ion-ios-arrow-back ons-back-button__icon"\n style="\n vertical-align: top;\n background-color: transparent;\n height: 44px;\n line-height: 44px;\n font-size: 36px;\n margin-left: 8px;\n margin-right: 2px;\n width: 16px;\n display: inline-block;\n padding-top: 1px;"></i>\n\n <span\n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;"\n class="back-button__label"></span>\n </span>\n '),MaterialTemplateElement=util.createElement('\n <span class="toolbar-button toolbar-button--material">\n <i class="zmdi zmdi-arrow-left"></i>\n </span>\n '),scheme={".toolbar-button--quiet":"toolbar-button--*"},BackButtonElement=function(_ons$_BaseElement){function BackButtonElement(){_classCallCheck(this,BackButtonElement),_get(Object.getPrototypeOf(BackButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BackButtonElement,_ons$_BaseElement),_createClass(BackButtonElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var toolbar=ons._util.findParent(this,"ons-toolbar"),template=void 0;template=toolbar&&ons._util.hasModifier(toolbar,"material")?MaterialTemplateElement.cloneNode(!0):iOSTemplateElement.cloneNode(!0);for(var inner=template.querySelector(".back-button__label");this.childNodes[0];)inner.appendChild(this.childNodes[0]);this.appendChild(template)}},{key:"_onClick",value:function(){var navigator=util.findParent(this,"ons-navigator");navigator&&navigator.popPage({cancelIfRunning:!0})}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}}]),BackButtonElement}(ons._BaseElement);window.OnsBackButtonElement||(window.OnsBackButtonElement=document.registerElement("ons-back-button",{prototype:BackButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"bottom-bar--*"},ModifierUtil=ons._internal.ModifierUtil,BottomToolbarElement=function(_ons$_BaseElement){function BottomToolbarElement(){_classCallCheck(this,BottomToolbarElement),_get(Object.getPrototypeOf(BottomToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BottomToolbarElement,_ons$_BaseElement),_createClass(BottomToolbarElement,[{key:"createdCallback",value:function(){this.classList.add("bottom-bar"),this.style.zIndex="0",this._update(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("inline"===name)this._update();else if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme)}},{key:"_update",value:function(){var inline="string"==typeof this.getAttribute("inline");this.style.position=inline?"static":"absolute"}}]),BottomToolbarElement}(ons._BaseElement);window.OnsBottomToolbarElement||(window.OnsBottomToolbarElement=document.registerElement("ons-bottom-toolbar",{prototype:BottomToolbarElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"button--*"},ModifierUtil=ons._internal.ModifierUtil,ButtonElement=function(_ons$_BaseElement){function ButtonElement(){_classCallCheck(this,ButtonElement),_get(Object.getPrototypeOf(ButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ButtonElement,_ons$_BaseElement),_createClass(ButtonElement,[{key:"createdCallback",value:function(){this.classList.add("button"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ButtonElement}(ons._BaseElement);window.OnsButtonElement||(window.OnsButtonElement=document.registerElement("ons-button",{prototype:ButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,scheme={"":"carousel-item--*"},CarouselItemElement=function(_ons$_BaseElement){function CarouselItemElement(){_classCallCheck(this,CarouselItemElement),_get(Object.getPrototypeOf(CarouselItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselItemElement,_ons$_BaseElement),_createClass(CarouselItemElement,[{key:"createdCallback",value:function(){this.style.width="100%",ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),CarouselItemElement}(ons._BaseElement);window.OnsCarouselItemElement||(window.OnsCarouselItemElement=document.registerElement("ons-carousel-item",{prototype:CarouselItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,util=ons._util,scheme={"":"carousel--*"},VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().height),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalWidth=this.getBoundingClientRect().width||0,finalWidth=totalWidth-parseInt(computedStyle.paddingLeft,10)-parseInt(computedStyle.paddingRight,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=sizeAttr,children[i].style.width=finalWidth+"px",children[i].style.visibility="visible",children[i].style.top=i*sizeInfo.number+sizeInfo.unit}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().width),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalHeight=this.getBoundingClientRect().height||0,finalHeight=totalHeight-parseInt(computedStyle.paddingTop,10)-parseInt(computedStyle.paddingBottom,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=finalHeight+"px",children[i].style.width=sizeAttr,children[i].style.visibility="visible",children[i].style.left=i*sizeInfo.number+sizeInfo.unit}},CarouselElement=function(_ons$_BaseElement){function CarouselElement(){_classCallCheck(this,CarouselElement),_get(Object.getPrototypeOf(CarouselElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselElement,_ons$_BaseElement),_createClass(CarouselElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"_onResize",value:function(){this.refresh()}},{key:"_onDirectionChange",value:function(){this._isVertical()?(this.style.overflowX="auto",this.style.overflowY=""):(this.style.overflowX="",this.style.overflowY="auto"),this.refresh()}},{key:"_saveLastState",value:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this.getCarouselItemCount(),width:this._getCarouselItemSize()*this.getCarouselItemCount()}}},{key:"_getCarouselItemSize",value:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")}},{key:"_getInitialIndex",value:function(){var index=parseInt(this.getAttribute("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this.getCarouselItemCount()-1),0)}},{key:"_getCarouselItemSizeAttr",value:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this.getAttribute(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"}},{key:"_decomposeSizeString",value:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}}},{key:"_setupInitialIndex",value:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)}},{key:"setSwipeable",value:function(swipeable){swipeable?this.setAttribute("swipeable",""):this.removeAttribute("swipeable")}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"setAutoScrollRatio",value:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this.setAttribute("auto-scroll-ratio",ratio)}},{key:"getAutoScrollRatio",value:function(){var attr=this.getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio}},{key:"setActiveCarouselItemIndex",value:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this.getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll();this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()}},{key:"getActiveCarouselItemIndex",value:function(){var scroll=this._scroll,count=this.getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;var i=void 0;for(i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i}},{key:"next",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)}},{key:"prev",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)}},{key:"setAutoScrollEnabled",value:function(enabled){enabled?this.setAttribute("auto-scroll",""):this.removeAttribute("auto-scroll")}},{key:"isAutoScrollEnabled",value:function(){return this.hasAttribute("auto-scroll")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setOverscrollable",value:function(scrollable){scrollable?this.setAttribute("overscrollable",""):this.removeAttribute("overscrollable")}},{key:"isOverscrollable",value:function(){return this.hasAttribute("overscrollable")}},{key:"_isEnabledChangeEvent",value:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize}},{key:"_isVertical",value:function(){return"vertical"===this.getAttribute("direction")}},{key:"_prepareEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this,{dragMinDistance:1}),this._gestureDetector.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.on("dragend",this._boundOnDragEnd),window.addEventListener("resize",this._boundOnResize,!0)}},{key:"_removeEventListeners",value:function(){this._gestureDetector.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),window.removeEventListener("resize",this._boundOnResize,!0)}},{key:"_tryFirePostChangeEvent",value:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,util.triggerElementEvent(this,"postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}}},{key:"_onDrag",value:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}}},{key:"_onDragEnd",value:function(event){var _this=this;if(this._currentElementSize=void 0,this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;util.triggerElementEvent(this,"overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){return _this._scrollToKillOverScroll()})}}),waitForAction||this._scrollToKillOverScroll()}else this._startMomentumScroll();this._lastDragEvent=null,event.gesture.preventDefault()}}},{key:"_mixin",value:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))}},{key:"_startMomentumScroll",value:function(){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,_scroll=this._normalizeScrollPosition(this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta));this._scroll=_scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}}},{key:"_normalizeScrollPosition",value:function(scroll){var _this2=this,max=this._calculateMaxScroll();if(!this.isAutoScrollEnabled())return Math.max(0,Math.min(max,scroll));var _ret=function(){for(var arr=[],size=_this2._getCarouselItemSize(),i=0;i<_this2.getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=_this2._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=_this2.getAutoScrollRatio()?{v:lastScroll}:scrollRatio>_this2.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?{v:arr[1]}:{v:arr[0]}}();return"object"==typeof _ret?_ret.v:void 0}},{key:"_getCarouselItemElements",value:function(){return ons._util.arrayFrom(this.children).filter(function(child){return"ons-carousel-item"===child.nodeName.toLowerCase()})}},{key:"_scrollTo",value:function(scroll,options){var _this3=this;options=options||{};var isOverscrollable=this.isOverscrollable(),normalizeScroll=function(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=_this3._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll};options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"
}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)}},{key:"_calculateMaxScroll",value:function(){var max=this.getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)}},{key:"_isOverScroll",value:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1}},{key:"_getOverScrollDirection",value:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"}},{key:"_scrollToKillOverScroll",value:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=0);var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=maxScroll)):void 0}},{key:"getCarouselItemCount",value:function(){return this._getCarouselItemElements().length}},{key:"refresh",value:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var _scroll2=this._scroll;this._isOverScroll(_scroll2)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(_scroll2=this._normalizeScrollPosition(_scroll2)),this._scrollTo(_scroll2))}this._saveLastState(),util.triggerElementEvent(this,"refresh",{carousel:this})}}},{key:"first",value:function(){this.setActiveCarouselItemIndex(0)}},{key:"last",value:function(){this.setActiveCarouselItemIndex(Math.max(this.getCarouselItemCount()-1,0))}},{key:"attachedCallback",value:function(){this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name&&this._onDirectionChange())}},{key:"detachedCallback",value:function(){this._removeEventListeners()}}]),CarouselElement}(ons._BaseElement);window.OnsCarouselElement||(window.OnsCarouselElement=document.registerElement("ons-carousel",{prototype:CarouselElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ColumnElement=function(_ons$_BaseElement){function ColumnElement(){_classCallCheck(this,ColumnElement),_get(Object.getPrototypeOf(ColumnElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ColumnElement,_ons$_BaseElement),_createClass(ColumnElement,[{key:"createdCallback",value:function(){this.getAttribute("width")&&this._updateWidth()}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name&&this._updateWidth()}},{key:"_updateWidth",value:function(){var width=this.getAttribute("width");"string"==typeof width&&(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,this.style.webkitBoxFlex="0",this.style.webkitFlex="0 0 "+width,this.style.mozBoxFlex="0",this.style.mozFlex="0 0 "+width,this.style.msFlex="0 0 "+width,this.style.flex="0 0 "+width,this.style.maxWidth=width)}}]),ColumnElement}(ons._BaseElement);window.OnsColElement||(window.OnsColElement=document.registerElement("ons-col",{prototype:ColumnElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".dialog":"dialog--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidDialogAnimator=ons._internal.AndroidDialogAnimator,IOSDialogAnimator=ons._internal.IOSDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,DialogAnimator=ons._internal.DialogAnimator,templateSource=util.createElement('\n <div>\n <div class="dialog-mask"></div>\n <div class="dialog"></div>\n </div>\n '),_animatorDict={"default":ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,fade:ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,slide:SlideDialogAnimator,none:DialogAnimator},DialogElement=function(_ons$_BaseElement){function DialogElement(){_classCallCheck(this,DialogElement),_get(Object.getPrototypeOf(DialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(DialogElement,_ons$_BaseElement),_createClass(DialogElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:DialogAnimator,baseClassName:"DialogAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"_compile",value:function(){var style=this.getAttribute("style");this.style.display="none";var template=templateSource.cloneNode(!0),dialog=template.children[1];for(style&&dialog.setAttribute("style",style);this.firstChild;)dialog.appendChild(this.firstChild);for(;template.firstChild;)this.appendChild(template.firstChild);this._dialog.style.zIndex=20001,this._mask.style.zIndex=2e4,this.setAttribute("no-status-bar-fill","")}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this,"cancel")}})}},{key:"show",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"preshow",{dialog:this,cancel:function(){_cancel2=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock();_this2.style.display="block",_this2._mask.style.opacity="1";var animator=_this2._animatorFactory.newAnimator(options);animator.show(_this2,function(){_this2._visible=!0,unlock(),util.triggerElementEvent(_this2,"postshow",{dialog:_this2}),callback()})})}},{key:"hide",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{dialog:this,cancel:function(){_cancel3=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock(),animator=_this3._animatorFactory.newAnimator(options);animator.hide(_this3,function(){_this3.style.display="none",_this3._visible=!1,unlock(),util.triggerElementEvent(_this3,"posthide",{dialog:_this3}),callback()})})}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"isShown",value:function(){return this._visible}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_mask",get:function(){return util.findChild(this,".dialog-mask")}},{key:"_dialog",get:function(){return util.findChild(this,".dialog")}}]),DialogElement}(ons._BaseElement);window.OnsDialogElement||(window.OnsDialogElement=document.registerElement("ons-dialog",{prototype:DialogElement.prototype}),window.OnsDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof DialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"fab--*"},ModifierUtil=ons._internal.ModifierUtil,FabElement=function(_ons$_BaseElement){function FabElement(){_classCallCheck(this,FabElement),_get(Object.getPrototypeOf(FabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(FabElement,_ons$_BaseElement),_createClass(FabElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this._updatePosition(),this.show()}},{key:"_compile",value:function(){var content=document.createElement("span");content.classList.add("fab__icon");ons._util.arrayFrom(this.childNodes).forEach(function(element){return content.appendChild(element)});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("position"===name&&this._updatePosition())}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(1)",this.style.webkitTransform="scale(1)"}},{key:"hide",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(0)",this.style.webkitTransform="scale(0)"}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return"scale(1)"===this.style.transform&&"none"!==this.style.display}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}}]),FabElement}(ons._BaseElement);window.OnsFabElement||(window.OnsFabElement=document.registerElement("ons-fab",{prototype:FabElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var GestureDetectorElement=function(_ons$_BaseElement){function GestureDetectorElement(){_classCallCheck(this,GestureDetectorElement),_get(Object.getPrototypeOf(GestureDetectorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(GestureDetectorElement,_ons$_BaseElement),_createClass(GestureDetectorElement,[{key:"createdCallback",value:function(){this._gestureDetector=new ons.GestureDetector(this)}}]),GestureDetectorElement}(ons._BaseElement);window.OnsGestureDetectorElement||(window.OnsGestureDetectorElement=document.registerElement("ons-gesture-detector",{prototype:GestureDetectorElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var IconElement=function(_ons$_BaseElement){function IconElement(){_classCallCheck(this,IconElement),_get(Object.getPrototypeOf(IconElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(IconElement,_ons$_BaseElement),_createClass(IconElement,[{key:"createdCallback",value:function(){this._update()}},{key:"attributeChangedCallback",value:function(name,last,current){-1!==["icon","size"].indexOf(name)&&this._update()}},{key:"_update",value:function(){var _this=this;this._cleanClassAttribute();var builded=this._buildClassAndStyle(this);for(var key in builded.style)builded.style.hasOwnProperty(key)&&(this.style[key]=builded.style[key]);builded.classList.forEach(function(className){return _this.classList.add(className)})}},{key:"_cleanClassAttribute",value:function(){var classList=this.classList;Array.apply(null,this.classList).filter(function(klass){return"fa"===klass||0===klass.indexOf("fa-")||0===klass.indexOf("ion-")||0===klass.indexOf("zmdi-")}).forEach(function(className){classList.remove(className)}),classList.remove("zmdi"),classList.remove("ons-icon--ion")}},{key:"_buildClassAndStyle",value:function(){var classList=["ons-icon"],style={},iconName=this._iconName;0===iconName.indexOf("ion-")?(classList.push(iconName),classList.push("ons-icon--ion")):0===iconName.indexOf("fa-")?(classList.push(iconName),classList.push("fa")):0===iconName.indexOf("md-")?(classList.push("zmdi"),classList.push("zmdi-"+iconName.split(/\-(.+)?/)[1])):(classList.push("fa"),classList.push("fa-"+iconName));var size=""+this.getAttribute("size");return size.match(/^[1-5]x|lg$/)?(classList.push("fa-"+size),this.style.removeProperty("font-size")):style.fontSize=size,{classList:classList,style:style}}},{key:"_iconName",get:function(){return""+this.getAttribute("icon")}}]),IconElement}(ons._BaseElement);window.OnsIconElement||(window.OnsIconElement=document.registerElement("ons-icon",{prototype:IconElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__header--*"},ModifierUtil=ons._internal.ModifierUtil,ListHeaderElement=function(_ons$_BaseElement){function ListHeaderElement(){_classCallCheck(this,ListHeaderElement),_get(Object.getPrototypeOf(ListHeaderElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListHeaderElement,_ons$_BaseElement),_createClass(ListHeaderElement,[{key:"createdCallback",value:function(){this.classList.add("list__header"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListHeaderElement}(ons._BaseElement);window.OnsListHeaderElement||(window.OnsListHeaderElement=document.registerElement("ons-list-header",{prototype:ListHeaderElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__item--*"},ModifierUtil=ons._internal.ModifierUtil,ListItemElement=function(_ons$_BaseElement){function ListItemElement(){_classCallCheck(this,ListItemElement),_get(Object.getPrototypeOf(ListItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListItemElement,_ons$_BaseElement),_createClass(ListItemElement,[{key:"createdCallback",value:function(){this.classList.add("list__item"),ModifierUtil.initModifier(this,scheme),this._gestureDetector=new ons.GestureDetector(this),this._boundOnDrag=this._onDrag.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("drag",this._boundOnDrag)}},{key:"detachedCallback",value:function(){this.removeEventListener("drag",this._boundOnDrag)}},{key:"_onDrag",value:function(event){var g=event.gesture;this._shouldLockOnDrag()&&["left","right"].indexOf(g.direction)>-1&&g.preventDefault()}},{key:"_shouldLockOnDrag",value:function(){return this.hasAttribute("lock-on-drag")}}]),ListItemElement}(ons._BaseElement);window.OnsListItemElement||(window.OnsListItemElement=document.registerElement("ons-list-item",{prototype:ListItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list--*"},ModifierUtil=ons._internal.ModifierUtil,ListElement=function(_ons$_BaseElement){function ListElement(){_classCallCheck(this,ListElement),_get(Object.getPrototypeOf(ListElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListElement,_ons$_BaseElement),_createClass(ListElement,[{key:"createdCallback",value:function(){this.classList.add("list"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListElement}(ons._BaseElement);window.OnsListElement||(window.OnsListElement=document.registerElement("ons-list",{prototype:ListElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".text-input--material":"text-input--material--*",".text-input--material__label":"text-input--material__label--*"},ModifierUtil=ons._internal.ModifierUtil,INPUT_ATTRIBUTES=["autocapitalize","autocomplete","autocorrect","autofocus","disabled","inputmode","max","maxlength","min","minlength","name","pattern","placeholder","readonly","size","step","type","validator","value"],MaterialInputElement=function(_ons$_BaseElement){function MaterialInputElement(){_classCallCheck(this,MaterialInputElement),_get(Object.getPrototypeOf(MaterialInputElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(MaterialInputElement,_ons$_BaseElement),_createClass(MaterialInputElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateLabel(),this._updateLabelColor(),this._updateBoundAttributes(),this._boundOnInput=this._onInput.bind(this),this._boundOnFocusin=this._onFocusin.bind(this),this._boundOnFocusout=this._onFocusout.bind(this),this._boundDelegateEvent=this._delegateEvent.bind(this)}},{key:"_compile",value:function(){this._input||(this.appendChild(document.createElement("input")),this._input.classList.add("text-input--material"),this.appendChild(document.createElement("span")),this._label.classList.add("text-input--material__label"))}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):"label"===name?this._updateLabel():INPUT_ATTRIBUTES.indexOf(name)>=0?this._updateBoundAttributes():void 0}},{key:"attachedCallback",value:function(){this._input.addEventListener("input",this._boundOnInput),this._input.addEventListener("focusin",this._boundOnFocusin),this._input.addEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"detachedCallback",value:function(){this._input.removeEventListener("input",this._boundOnInput),this._input.removeEventListener("focusin",this._boundOnFocusin),this._input.removeEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"_setLabel",value:function(value){"undefined"!=typeof this._label.textContent?this._label.textContent=value:this._label.innerText=value}},{key:"_updateLabel",value:function(){this._setLabel(this.hasAttribute("label")?this.getAttribute("label"):"")}},{key:"_updateBoundAttributes",value:function(){var _this=this;INPUT_ATTRIBUTES.forEach(function(attr){_this.hasAttribute(attr)?_this._input.setAttribute(attr,_this.getAttribute(attr)):_this._input.removeAttribute(attr)})}},{key:"_updateLabelColor",value:function(){this.value.length>0&&this._input===document.activeElement?this._label.style.color="":this._label.style.color="rgba(0, 0, 0, 0.5)"}},{key:"_updateLabelClass",value:function(){""===this.value?this._label.classList.remove("text-input--material__label--active"):this._label.classList.add("text-input--material__label--active")}},{key:"_delegateEvent",value:function(event){var e=new CustomEvent(event.type,{bubbles:!1,cancelable:!0});return this.dispatchEvent(e)}},{key:"_onInput",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusin",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusout",value:function(event){this._updateLabelColor()}},{key:"_input",get:function(){return this.querySelector("input")}},{key:"_label",get:function(){return this.querySelector("span")}},{key:"value",get:function(){return this._input.value},set:function(val){return this._input.value=val,this._onInput(),this._input.val}}]),MaterialInputElement}(ons._BaseElement);window.OnsMaterialInputElement||(window.OnsMaterialInputElement=document.registerElement("ons-material-input",{prototype:MaterialInputElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"modal--*",modal__content:"modal--*__content"},AnimatorFactory=ons._internal.AnimatorFactory,ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=ons._internal.FadeModalAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":ModalAnimator,fade:FadeModalAnimator,none:ModalAnimator},ModalElement=function(_ons$_BaseElement){function ModalElement(){_classCallCheck(this,ModalElement),_get(Object.getPrototypeOf(ModalElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ModalElement,_ons$_BaseElement),_createClass(ModalElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:ModalAnimator,baseClassName:"ModalAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"getDeviceBackButtonHandler",
value:function(){return this._deviceBackButtonHandler}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback),this._onDeviceBackButton=callback}},{key:"_onDeviceBackButton",value:function(){}},{key:"_compile",value:function(){this.style.display="none",this.classList.add("modal");var wrapper=document.createElement("div");for(wrapper.classList.add("modal__content");this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),wrapper.insertBefore(node,null)}this.appendChild(wrapper)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy()}},{key:"attachedCallback",value:function(){setImmediate(this._ensureNodePosition.bind(this)),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this))}},{key:"_ensureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerExtraElement(this)}}},{key:"isShown",value:function(){return"none"!==this.style.display}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock(),animator=_this._animatorFactory.newAnimator(options);_this.style.display="table",animator.show(_this,function(){unlock(),callback()})})}},{key:"toggle",value:function(){return this.isShown()?this.hide.apply(this,arguments):this.show.apply(this,arguments)}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",unlock(),callback()})})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ModalElement}(ons._BaseElement);window.OnsModalElement||(window.OnsModalElement=document.registerElement("ons-modal",{prototype:ModalElement.prototype}),window.OnsModalElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof ModalAnimator))throw new Error('"Animator" param must inherit ModalAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var AnimatorFactory=ons._internal.AnimatorFactory,NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=ons._internal.IOSSlideNavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=ons._internal.SimpleSlideNavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=ons._internal.LiftNavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=ons._internal.FadeNavigatorTransitionAnimator,NoneNavigatorTransitionAnimator=ons._internal.NoneNavigatorTransitionAnimator,util=ons._util,NavigatorPage=ons._internal.NavigatorPage,_animatorDict={"default":ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,slide:ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,simpleslide:SimpleSlideNavigatorTransitionAnimator,lift:LiftNavigatorTransitionAnimator,fade:FadeNavigatorTransitionAnimator,none:NoneNavigatorTransitionAnimator},rewritables={ready:function(navigatorElement,callback){callback()},link:function(navigatorElement,target,callback){callback(target)}},NavigatorElement=function(_ons$_BaseElement){function NavigatorElement(){_classCallCheck(this,NavigatorElement),_get(Object.getPrototypeOf(NavigatorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(NavigatorElement,_ons$_BaseElement),_createClass(NavigatorElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._pages=[],this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._isPushing=this._isPopping=!1,this._initialHTML=this.innerHTML,this.innerHTML="",this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:NavigatorTransitionAnimator,baseClassName:"NavigatorTransitionAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"canPopPage",value:function(){return this._pages.length>1}},{key:"replacePage",value:function(page,options){var _this=this;options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};return options.onTransitionEnd=function(){_this._pages.length>1&&_this._pages[_this._pages.length-2].destroy(),onTransitionEnd()},this.pushPage(page,options)}},{key:"popPage",value:function(options){var _this2=this;options=options||{},options.cancelIfRunning&&this._isPopping||(options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),this._doorLock.waitUnlock(function(){if(_this2._pages.length<=1)throw new Error("ons-navigator's page stack is empty.");if(!_this2._emitPrePopEvent()){var unlock=_this2._doorLock.lock();options.refresh?!function(){var index=_this2.pages.length-2;if(!_this2._pages[index].page)throw new Error("Refresh option cannot be used with pages directly inside the Navigator. Use ons-template instead.");ons._internal.getPageHTMLAsync(_this2._pages[index].page).then(function(templateHTML){var element=_this2._createPageElement(templateHTML),pageObject=_this2._createPageObject(_this2._pages[index].page,element,options);rewritables.link(_this2,element,function(element){_this2.insertBefore(element,_this2._pages[index]?_this2._pages[index].element:null),_this2._pages.splice(index,0,pageObject),_this2._pages[index+1].destroy(),_this2._popPage(options,unlock)})})}():_this2._popPage(options,unlock)}}))}},{key:"_popPage",value:function(options,unlock){var _this3=this;options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var leavePage=this._pages.pop(),enterPage=this._pages[this._pages.length-1];leavePage.element._hide(),enterPage&&(enterPage.element.style.display="block",enterPage.element._show());var eventDetail={leavePage:leavePage,enterPage:this._pages[this._pages.length-1],navigator:this},callback=function(){leavePage.destroy(),_this3._isPopping=!1,unlock();var event=util.triggerElementEvent(_this3,"postpop",eventDetail);event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()};this._isPopping=!0;var animator=this._animatorFactory.newAnimator(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)}},{key:"insertPage",value:function(index,page,options){var _this4=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);return index=this._normalizeIndex(index),index>=this.pages.length?this.pushPage.apply(this,[].slice.call(arguments,1)):void this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock();ons._internal.getPageHTMLAsync(page).then(function(templateHTML){var element=_this4._createPageElement(templateHTML),pageObject=_this4._createPageObject(page,element,options);rewritables.link(_this4,element,function(element){element.style.display="none",_this4.insertBefore(element,_this4._pages[index].element),_this4._pages.splice(index,0,pageObject),setTimeout(function(){unlock(),element=null},1e3/60)})})})}},{key:"_normalizeIndex",value:function(index){return 0>index&&(index=Math.abs(this.pages.length+index)%this.pages.length),index}},{key:"getCurrentPage",value:function(){if(this._pages.length<=0)throw new Error("Invalid state");return this._pages[this._pages.length-1]}},{key:"_show",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._show()}},{key:"_hide",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._hide()}},{key:"_destroy",value:function(){for(var i=this._pages.length-1;i>=0;i--)this._pages[i].destroy();this.remove()}},{key:"_onDeviceBackButton",value:function(event){this._pages.length>1?this.popPage():event.callParentHandler()}},{key:"resetToPage",value:function(page,options){var _this5=this;options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){for(;_this5._pages.length>1;)_this5._pages.shift().destroy();onTransitionEnd()},(void 0===page||""===page)&&(this.hasAttribute("page")?page=this.getAttribute("page"):(options.pageHTML=this._initialHTML,page="")),this.pushPage(page,options)}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){var _this6=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),rewritables.ready(this,function(){if(0===_this6._pages.length)if(_this6.getAttribute("page"))_this6.pushPage(_this6.getAttribute("page"),{animation:"none"});else{var element=_this6._createPageElement(_this6._initialHTML||"");_this6._pushPageDOM(_this6._createPageObject("",element,{}),function(){})}})}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null}},{key:"pushPage",value:function(page,options){var _this7=this;if(options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),!options.cancelIfRunning||!this._isPushing){if(options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){return _this7._pushPage(page,options)})}}},{key:"_pushPage",value:function(page,options){var _this8=this,unlock=this._doorLock.lock(),done=function(){unlock()},run=function(templateHTML){var element=_this8._createPageElement(templateHTML);_this8._pushPageDOM(_this8._createPageObject(page,element,options),done)};options.pageHTML?run(options.pageHTML):ons._internal.getPageHTMLAsync(page).then(run)}},{key:"_pushPageDOM",value:function(pageObject,unlock){var _this9=this;unlock=unlock||function(){};var element=pageObject.element,options=pageObject.options,eventDetail={enterPage:pageObject,leavePage:this._pages[this._pages.length-1],navigator:this};this._pages.push(pageObject);var done=function(){_this9._pages[_this9._pages.length-2]&&(_this9._pages[_this9._pages.length-2].element.style.display="none"),_this9._isPushing=!1,unlock(),util.triggerElementEvent(_this9,"postpush",eventDetail),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null};this._isPushing=!0,rewritables.link(this,element,function(element){CustomElements.upgrade(element),setTimeout(function(){if(_this9._pages.length>1){var leavePage=_this9._pages.slice(-2)[0],enterPage=_this9._pages.slice(-1)[0];_this9.appendChild(element),leavePage.element._hide(),enterPage.element._show(),options.animator.push(enterPage,leavePage,done)}else _this9.appendChild(element),element._show(),done()},1e3/60)})}},{key:"bringPageTop",value:function(item,options){var _this10=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(!(options.cancelIfRunning&&this._isPushing||this._emitPrePushEvent())){var index=void 0,page=void 0;if("string"==typeof item)page=item,index=this._lastIndexOfPage(page);else{if("number"!=typeof item)throw new Error("First argument must be a page name or the index of an existing page. You supplied "+item);if(index=this._normalizeIndex(item),item>=this._pages.length)throw new Error("The provided index does not match an existing page.");page=this._pages[index].page}0>index?this._doorLock.waitUnlock(function(){return _this10._pushPage(page,options)}):index<this._pages.length-1&&this._doorLock.waitUnlock(function(){var unlock=_this10._doorLock.lock(),done=function(){unlock()},pageObject=_this10._pages.splice(index,1)[0];pageObject.element.style.display="block",pageObject.element.setAttribute("_skipinit",""),options.animator=_this10._animatorFactory.newAnimator(options),pageObject.options=options,_this10._pushPageDOM(pageObject,done)})}}},{key:"_lastIndexOfPage",value:function(page){var index=void 0;for(index=this._pages.length-1;index>=0&&this._pages[index].page!==page;index--);return index}},{key:"_emitPrePushEvent",value:function(){var isCanceled=!1;return util.triggerElementEvent(this,"prepush",{navigator:this,currentPage:this._pages.length>0?this.getCurrentPage():void 0,cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_emitPrePopEvent",value:function(){var isCanceled=!1,leavePage=this.getCurrentPage();return util.triggerElementEvent(this,"prepop",{navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this._pages[this._pages.length-2],cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_createPageObject",value:function(page,element,options){return options.animator=this._animatorFactory.newAnimator(options),new NavigatorPage({page:page,element:element,options:options,navigator:this})}},{key:"_createPageElement",value:function(templateHTML){var pageElement=util.createElement(ons._internal.normalizePageHTML(templateHTML));if("ons-page"!==pageElement.nodeName.toLowerCase())throw new Error('You must supply an "ons-page" element to "ons-navigator".');return pageElement}},{key:"pages",get:function(){return this._pages.slice(0)}}]),NavigatorElement}(ons._BaseElement);window.OnsNavigatorElement||(window.OnsNavigatorElement=document.registerElement("ons-navigator",{prototype:NavigatorElement.prototype}),window.OnsNavigatorElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof NavigatorTransitionAnimator))throw new Error('"Animator" param must inherit NavigatorTransitionAnimator');_animatorDict[name]=Animator},window.OnsNavigatorElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"page--*",".page__content":"page--*__content",".page__background":"page--*__background"},ModifierUtil=ons._internal.ModifierUtil,nullToolbarElement=document.createElement("ons-toolbar"),util=ons._util,PageElement=function(_ons$_BaseElement){function PageElement(){_classCallCheck(this,PageElement),_get(Object.getPrototypeOf(PageElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PageElement,_ons$_BaseElement),_createClass(PageElement,[{key:"createdCallback",value:function(){this.classList.add("page"),this._compile(),ModifierUtil.initModifier(this,scheme),this._isShown=!1,this._isMuted=this.hasAttribute("_muted"),this._skipInit=this.hasAttribute("_skipinit"),this.eventDetail={page:this}}},{key:"attachedCallback",value:function(){this._isMuted||(this._skipInit?this.removeAttribute("_skipinit"):util.triggerElementEvent(this,"init",this.eventDetail)),util.hasAnyComponentAsParent(this)||this._show()}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler||null}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback)}},{key:"_getContentElement",value:function(){var result=ons._util.findChild(this,".page__content");if(result)return result;throw Error('fail to get ".page__content" element.')}},{key:"_hasToolbarElement",value:function(){return!!ons._util.findChild(this,"ons-toolbar")}},{key:"_canAnimateToolbar",value:function(){var toolbar=ons._util.findChild(this,"ons-toolbar");if(toolbar)return!0;for(var elements=this._getContentElement().children,i=0;i<elements.length;i++)if("ons-toolbar"===elements[i].nodeName.toLowerCase()&&!elements[i].hasAttribute("inline"))return!0;return!1}},{key:"_getBackgroundElement",value:function(){var result=ons._util.findChild(this,".page__background");if(result)return result;throw Error('fail to get ".page__background" element.')}},{key:"_getBottomToolbarElement",value:function(){return ons._util.findChild(this,"ons-bottom-toolbar")||ons._internal.nullElement}},{key:"_getToolbarElement",value:function(){return ons._util.findChild(this,"ons-toolbar")||nullToolbarElement}},{key:"_registerToolbar",value:function(element){this._getContentElement().setAttribute("no-status-bar-fill",""),ons._util.findChild(this,".page__status-bar-fill")?this.insertBefore(element,this.children[1]):this.insertBefore(element,this.children[0])}},{key:"_registerBottomToolbar",value:function(element){if(!ons._util.findChild(this,".page__status-bar-fill")){var fill=document.createElement("div");fill.classList.add("page__bottom-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0]),this.insertBefore(element,null)}}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("_muted"===name?this._isMuted=this.hasAttribute("_muted"):"_skipinit"===name&&(this._skipInit=this.hasAttribute("_skipinit")))}},{key:"_compile",value:function(){if(!ons._util.findChild(this,".page__background")||!ons._util.findChild(this,".page__content")){var background=document.createElement("div");background.classList.add("page__background");var content=document.createElement("div");for(content.classList.add("page__content");this.childNodes[0];)content.appendChild(this.childNodes[0]);this.hasAttribute("style")&&(background.setAttribute("style",this.getAttribute("style")),this.removeAttribute("style",null));var fragment=document.createDocumentFragment();fragment.appendChild(background),fragment.appendChild(content),this.appendChild(fragment)}}},{key:"_registerExtraElement",value:function(element){var extra=ons._util.findChild(this,".page__extra");extra||(extra=document.createElement("div"),extra.classList.add("page__extra"),extra.style.zIndex="10001",this.insertBefore(extra,null)),extra.insertBefore(element,null)}},{key:"_tryToFillStatusBar",value:function(){if(ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("page__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_show",value:function(){!this.isShown&&ons._util.isAttached(this)&&(this.isShown=!0,this._isMuted||util.triggerElementEvent(this,"show",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_show"))}},{key:"_hide",value:function(){this.isShown&&(this.isShown=!1,this._isMuted||util.triggerElementEvent(this,"hide",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_hide"))}},{key:"_destroy",value:function(){this._hide(),this._isMuted||util.triggerElementEvent(this,"destroy",this.eventDetail),this.getDeviceBackButtonHandler()&&this.getDeviceBackButtonHandler().destroy(),ons._util.propagateAction(this._getContentElement(),"_destroy"),this.remove()}},{key:"isShown",get:function(){return this._isShown},set:function(value){this._isShown=value}}]),PageElement}(ons._BaseElement);window.OnsPageElement||(window.OnsPageElement=document.registerElement("ons-page",{prototype:PageElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".popover":"popover--*",".popover__content":"popover__content--*"},PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=ons._internal.FadePopoverAnimator,templateSource=util.createElement('\n <div>\n <div class="popover-mask"></div>\n <div class="popover">\n <div class="popover__content"></div>\n <div class="popover__arrow"></div>\n </div>\n </div>\n '),AnimatorFactory=ons._internal.AnimatorFactory,_animatorDict={fade:FadePopoverAnimator,none:PopoverAnimator},PopoverElement=function(_ons$_BaseElement){function PopoverElement(){_classCallCheck(this,PopoverElement),_get(Object.getPrototypeOf(PopoverElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PopoverElement,_ons$_BaseElement),_createClass(PopoverElement,[{key:"createdCallback",value:function(){this._compile(),this.style.display="none",ModifierUtil.initModifier(this,scheme),this._mask.style.zIndex="20000",this._popover.style.zIndex="20001",this.hasAttribute("mask-color")&&(this._mask.style.backgroundColor=this.getAttribute("mask-color")),this._visible=!1,this._doorLock=new DoorLock,this._boundOnChange=this._onChange.bind(this),this._boundCancel=this._cancel.bind(this),this._animatorFactory=this._createAnimatorFactory()}},{key:"_createAnimatorFactory",value:function(){return new AnimatorFactory({animators:_animatorDict,baseClass:PopoverAnimator,baseClassName:"PopoverAnimator",defaultAnimation:this.getAttribute("animation")||"fade"})}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_setDirection",value:function(direction){var arrowPosition=void 0;if("up"===direction)arrowPosition="bottom";else if("left"===direction)arrowPosition="right";else if("down"===direction)arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");arrowPosition="left"}var popoverClassList=this._popover.classList;popoverClassList.remove("popover--up"),popoverClassList.remove("popover--down"),popoverClassList.remove("popover--left"),popoverClassList.remove("popover--right"),popoverClassList.add("popover--"+direction);var arrowClassList=this._arrow.classList;arrowClassList.remove("popover__top-arrow"),arrowClassList.remove("popover__bottom-arrow"),arrowClassList.remove("popover__left-arrow"),arrowClassList.remove("popover__right-arrow"),arrowClassList.add("popover__"+arrowPosition+"-arrow")}},{key:"_positionPopoverByDirection",value:function(target,direction){var el=this._popover,pos=target.getBoundingClientRect(),own=el.getBoundingClientRect(),arrow=el.children[1],offset=14,margin=6,radius=parseInt(window.getComputedStyle(el.querySelector(".popover__content")).borderRadius);arrow.style.top="",arrow.style.left="",this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.style.left=pos.right-pos.width-own.width-offset+"px":el.style.left=pos.right+offset+"px",el.style.top=pos.bottom-pos.height/2-own.height/2+"px"):("up"==direction?el.style.top=pos.bottom-pos.height-own.height-offset+"px":el.style.top=pos.bottom+offset+"px",el.style.left=pos.right-pos.width/2-own.width/2+"px"),own=el.getBoundingClientRect();var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow).width)),limit=margin+radius+diff+2;["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.style.top=Math.max(own.height/2+own.top-margin,limit)+"px",el.style.top=margin+"px"):own.bottom>window.innerHeight-margin&&(arrow.style.top=Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px",el.style.top=window.innerHeight-own.height-margin+"px"):own.left<margin?(arrow.style.left=Math.max(own.width/2+own.left-margin,limit)+"px",el.style.left=margin+"px"):own.right>window.innerWidth-margin&&(arrow.style.left=Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px",el.style.left=window.innerWidth-own.width-margin+"px"),el.removeAttribute("data-animit-orig-style")}},{key:"_positionPopover",value:function(target){for(var _this=this,directions=function(){return _this.hasAttribute("direction")?_this.getAttribute("direction").split(/\s+/):["up","down","left","right"]}(),position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return void this._positionPopoverByDirection(target,direction)}}},{key:"_onChange",value:function(){var _this2=this;setImmediate(function(){_this2._currentTarget&&_this2._positionPopover(_this2._currentTarget)})}},{key:"_compile",value:function(){var templateElement=templateSource.cloneNode(!0),content=templateElement.querySelector(".popover__content"),style=this.getAttribute("style");for(style&&this.removeAttribute("style");this.childNodes[0];)content.appendChild(this.childNodes[0]);for(;templateElement.children[0];)this.appendChild(templateElement.children[0]);style&&this._popover.setAttribute("style",style)}},{key:"show",value:function(target,options){var _this3=this;if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");if(options=options||{},options.animation&&!(options.animation in _animatorDict))throw new Error("Animator "+options.animation+" is not registered.");options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var canceled=!1;util.triggerElementEvent(this,"preshow",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock();_this3.style.display="block",_this3._currentTarget=target,_this3._positionPopover(target);var animator=_this3._animatorFactory.newAnimator(options);animator.show(_this3,function(){_this3._visible=!0,unlock(),util.triggerElementEvent(_this3,"postshow",{popover:_this3})})})}},{key:"hide",value:function(options){var _this4=this;options=options||{};var canceled=!1;util.triggerElementEvent(this,"prehide",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock(),animator=_this4._animatorFactory.newAnimator(options);animator.hide(_this4,function(){_this4.style.display="none",_this4._visible=!1,unlock(),util.triggerElementEvent(_this4,"posthide",{popover:_this4})})})}},{key:"isShown",value:function(){return this._visible}},{key:"attachedCallback",value:function(){this._mask.addEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._popover.addEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.addEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.addEventListener("resize",this._boundOnChange,!1)}},{key:"detachedCallback",value:function(){this._mask.removeEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._popover.removeEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.removeEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.removeEventListener("resize",this._boundOnChange,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._boundOnChange():("animation"===name||"animation-options"===name)&&(this._animatorFactory=this._createAnimatorFactory()))}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"_cancel",value:function(){this.isCancelable()&&this.hide()}},{key:"_mask",get:function(){return this.children[0]}},{key:"_popover",get:function(){return this.children[1]}},{key:"_content",get:function(){return this._popover.children[0]}},{key:"_arrow",get:function(){return this._popover.children[1]}}]),PopoverElement}(ons._BaseElement);window.OnsPopoverElement||(window.OnsPopoverElement=document.registerElement("ons-popover",{prototype:PopoverElement.prototype}),window.OnsPopoverElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof PopoverAnimator))throw new Error('"Animator" param must inherit PopoverAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),
Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".progress-bar":"progress-bar--*",".progress-circular":"progress-circular--*",".progress-circular__primary":"progress-circular__primary--*",".progress-circular__secondary":"progress-circular__secondary--*",".progress-bar__primary":"progress-bar__primary--*",".progress-bar__secondary":"progress-bar__secondary--*"},barTemplate=util.createElement('\n <div class="progress-bar">\n <div class="progress-bar__secondary"></div>\n <div class="progress-bar__primary"></div>\n </div>\n '),circularTemplate=util.createElement('\n <svg class="progress-circular">\n <circle class="progress-circular__secondary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n <circle class="progress-circular__primary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n </svg>\n '),ProgressElement=function(_ons$_BaseElement){function ProgressElement(){_classCallCheck(this,ProgressElement),_get(Object.getPrototypeOf(ProgressElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ProgressElement,_ons$_BaseElement),_createClass(ProgressElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme);if("value"===name||"secondary-value"===name)this._updateValue();else{if("type"===name)throw new Error("Can not change type attribute.");"indeterminate"===name&&this._updateDeterminate()}}},{key:"_updateDeterminate",value:function(){this.hasAttribute("indeterminate")?(this._template.classList.add("progress-"+this._type+"--indeterminate"),this._template.classList.remove("progress-"+this._type+"--determinate")):(this._template.classList.add("progress-"+this._type+"--determinate"),this._template.classList.remove("progress-"+this._type+"--indeterminate"))}},{key:"_updateValue",value:function(){if("bar"===this._type)this._primary.style.width=this.hasAttribute("value")?this.getAttribute("value")+"%":"0%",this._secondary.style.width=this.hasAttribute("secondary-value")?this.getAttribute("secondary-value")+"%":"0%";else{if(this.hasAttribute("value")){var per=Math.ceil(251.32*this.getAttribute("value")*.01);this._primary.style["stroke-dasharray"]=per+"%, 251.32%"}if(this.hasAttribute("secondary-value")){var per=Math.ceil(251.32*this.getAttribute("secondary-value")*.01);this._secondary.style["stroke-dasharray"]=per+"%, 251.32%"}}}},{key:"_compile",value:function(){"bar"===this._type?this._template=barTemplate.cloneNode(!0):this._template=circularTemplate.cloneNode(!0),this._primary=this._template.childNodes[3],this._secondary=this._template.childNodes[1],this._updateDeterminate(),this._updateValue(),this.appendChild(this._template)}},{key:"_type",get:function(){return this.hasAttribute("type")&&"circular"===this.getAttribute("type")?"circular":"bar"}}]),ProgressElement}(ons._BaseElement);window.OnsProgressElement||(window.OnsProgressElement=document.registerElement("ons-progress",{prototype:ProgressElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var STATE_INITIAL="initial",STATE_PREACTION="preaction",STATE_ACTION="action",util=ons._util,PullHookElement=function(_ons$_BaseElement){function PullHookElement(){_classCallCheck(this,PullHookElement),_get(Object.getPrototypeOf(PullHookElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PullHookElement,_ons$_BaseElement),_createClass(PullHookElement,[{key:"createdCallback",value:function(){if(this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parentElement,!this._pageElement.classList.contains("page__content")&&!this._pageElement.classList.contains("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragStart=this._onDragStart.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnScroll=this._onScroll.bind(this),this._currentTranslation=0,this._setState(STATE_INITIAL,!0),this._setStyle()}},{key:"_createScrollElement",value:function(){var scrollElement=util.createElement('<div class="scroll"><div>'),pageElement=this.parentElement;for(scrollElement.appendChild(this);pageElement.firstChild;)scrollElement.appendChild(pageElement.firstChild);return pageElement.appendChild(scrollElement),scrollElement}},{key:"_setStyle",value:function(){var height=this.getHeight();this.style.top="-"+height+"px",this.style.height=height+"px",this.style.lineHeight=height+"px"}},{key:"_onScroll",value:function(event){var element=this._pageElement;element.scrollTop<0&&(element.scrollTop=0)}},{key:"_generateTranslationTransform",value:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"}},{key:"_onDrag",value:function(event){var _this=this;if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var element=this._pageElement;if(element.scrollTop=this._startScroll-event.gesture.deltaY,element.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=Math.max(event.gesture.deltaY-this._startScroll,0);this._thresholdHeightEnabled()&&scroll>=this.getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){_this._setState(STATE_ACTION),_this._translateTo(_this.getHeight(),{animate:!0}),_this._waitForAction(_this._onDone.bind(_this))})):scroll>=this.getHeight()?this._setState(STATE_PREACTION):this._setState(STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}}},{key:"_onDragStart",value:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())}},{key:"_onDragEnd",value:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var _scroll=this._currentTranslation;_scroll>this.getHeight()?(this._setState(STATE_ACTION),this._translateTo(this.getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}}},{key:"setActionCallback",value:function(callback){this._callback=callback}},{key:"_waitForAction",value:function(done){this._callback instanceof Function?this._callback.call(null,done):done()}},{key:"_onDone",value:function(done){this._translateTo(0,{animate:!0}),this._setState(STATE_INITIAL)}},{key:"getHeight",value:function(){return parseInt(this.getAttribute("height")||"64",10)}},{key:"setHeight",value:function(height){this.setAttribute("height",height+"px"),this._setStyle()}},{key:"setThresholdHeight",value:function(thresholdHeight){this.setAttribute("threshold-height",thresholdHeight+"px")}},{key:"getThresholdHeight",value:function(){return parseInt(this.getAttribute("threshold-height")||"96",10)}},{key:"_thresholdHeightEnabled",value:function(){var th=this.getThresholdHeight();return th>0&&th>=this.getHeight()}},{key:"_setState",value:function(state,noEvent){var lastState=this._getState();this.setAttribute("state",state),noEvent||lastState===this._getState()||util.triggerElementEvent(this,"changestate",{pullHook:this,state:state,lastState:lastState})}},{key:"_getState",value:function(){return this.getAttribute("state")}},{key:"getCurrentState",value:function(){return this._getState()}},{key:"_getCurrentScroll",value:function(){return this._pageElement.scrollTop}},{key:"getPullDistance",value:function(){return this._currentTranslation}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"_isContentFixed",value:function(){return this.hasAttribute("fixed-content")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"_getScrollableElement",value:function(){return this._isContentFixed()?this:this._scrollElement}},{key:"_translateTo",value:function(scroll){var _this2=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(0!=this._currentTranslation||0!=scroll){var done=function(){0===scroll&&_this2._getScrollableElement().removeAttribute("style"),options.callback&&options.callback()};this._currentTranslation=scroll,options.animate?animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(done):animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)}).play(done)}}},{key:"_getMinimumScroll",value:function(){var scrollHeight=this._scrollElement.getBoundingClientRect().height,pageHeight=this._pageElement.getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0}},{key:"_createEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this._pageElement,{dragMinDistance:1,dragDistanceCorrection:!1}),this._gestureDetector.on("drag",this._boundOnDrag),this._gestureDetector.on("dragstart",this._boundOnDragStart),this._gestureDetector.on("dragend",this._boundOnDragEnd),this._scrollElement.parentElement.addEventListener("scroll",this._boundOnScroll,!1)}},{key:"_destroyEventListeners",value:function(){this._gestureDetector.off("drag",this._boundOnDrag),this._gestureDetector.off("dragstart",this._boundOnDragStart),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),this._gestureDetector=null,this._scrollElement.parentElement.removeEventListener("scroll",this._boundOnScroll,!1)}},{key:"attachedCallback",value:function(){this._createEventListeners()}},{key:"detachedCallback",value:function(){this._destroyEventListeners()}},{key:"attributeChangedCallback",value:function(name,last,current){}}]),PullHookElement}(ons._BaseElement);window.OnsPullHookElement||(window.OnsPullHookElement=document.registerElement("ons-pull-hook",{prototype:PullHookElement.prototype}),window.OnsPullHookElement.STATE_ACTION=STATE_ACTION,window.OnsPullHookElement.STATE_INITIAL=STATE_INITIAL,window.OnsPullHookElement.STATE_PREACTION=STATE_PREACTION)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var RippleElement=function(_ons$_BaseElement){function RippleElement(){_classCallCheck(this,RippleElement),_get(Object.getPrototypeOf(RippleElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(RippleElement,_ons$_BaseElement),_createClass(RippleElement,[{key:"createdCallback",value:function(){this.classList.add("ripple"),this._compile(),this._boundOnClick=this._onMouseDown.bind(this)}},{key:"_compile",value:function(){this._wave=document.createElement("span"),this._wave.classList.add("ripple__wave"),this.insertBefore(this._wave,this.children[0]),this.hasAttribute("color")&&(this._wave.style.background=this.getAttribute("color"))}},{key:"_updateTarget",value:function(){this.hasAttribute("target")&&"children"===this.getAttribute("target")?(this._target=this,this.style.display="inline-block",this.style.position="relative"):(this._target=this.parentNode,"static"===window.getComputedStyle(this._target).getPropertyValue("position")&&(this._target.style.position="relative"),this.style.display="block",this.style.position="absolute")}},{key:"_updateCenter",value:function(){this.hasAttribute("center")?this._center=!0:this._center=!1,this._wave.classList.remove("ripple__wave--done-center"),this._wave.classList.remove("ripple__wave--animate-center"),this._wave.classList.remove("ripple__wave--done"),this._wave.classList.remove("ripple__wave--animate")}},{key:"attributeChangedCallback",value:function(name,last,current){"target"===name&&this._updateTarget(),"color"===name&&(this._wave.style.background=current),"center"===name&&this._updateCenter()}},{key:"_isTouchDevice",value:function(){return"ontouchstart"in window||"onmsgesturechange"in window}},{key:"_addListener",value:function(){this._isTouchDevice()?this.addEventListener("touchstart",this._boundOnClick):this.addEventListener("mousedown",this._boundOnClick)}},{key:"_removeListener",value:function(){this._isTouchDevice()?this.removeEventListener("touchstart",this._boundOnClick):this.removeEventListener("mousedown",this._boundOnClick)}},{key:"attachedCallback",value:function(){this._updateCenter(),this._updateTarget(),this._addListener()}},{key:"detachedCallback",value:function(){this._removeListener()}},{key:"_onMouseDown",value:function(e){var _this=this,eventType=e.type,wave=this._wave,el=this._target,pos=el.getBoundingClientRect();if(!this.isDisabled()){this._center?(wave.classList.remove("ripple__wave--done-center"),wave.classList.remove("ripple__wave--animate-center")):(wave.classList.remove("ripple__wave--done"),wave.classList.remove("ripple__wave--animate"));var animationEnded=new Promise(function(resolve){var onAnimationEnd=function onAnimationEnd(){_this.removeEventListener("webkitAnimationEnd",onAnimationEnd),_this.removeEventListener("animationend",onAnimationEnd),resolve()};_this.addEventListener("webkitAnimationEnd",onAnimationEnd),_this.addEventListener("animationend",onAnimationEnd)}),mouseReleased=new Promise(function(resolve){var onMouseUp=function onMouseUp(){document.removeEventListener("webkitAnimationEnd",onMouseUp),document.removeEventListener("animationend",onMouseUp),resolve()};document.addEventListener("mouseup",onMouseUp),document.addEventListener("touchend",onMouseUp)});Promise.all([animationEnded,mouseReleased]).then(function(){_this._center?(wave.classList.remove("ripple__wave--animate-center"),wave.classList.add("ripple__wave--done-center")):(wave.classList.remove("ripple__wave--animate"),wave.classList.add("ripple__wave--done"))});var x=e.clientX,y=e.clientY;"touchstart"===eventType&&(x=e.changedTouches[0].clientX,y=e.changedTouches[0].clientY);var sizeX=void 0,sizeY=0;this._center?(sizeX=el.offsetWidth,sizeY=el.offsetHeight,sizeX=sizeX-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-left-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-right-width")),sizeY=sizeY-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-top-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-bottom-width"))):sizeX=sizeY=Math.max(el.offsetWidth,el.offsetHeight),wave.style.width=sizeX+"px",wave.style.height=sizeY+"px",x=x-pos.left-sizeX/2,y=y-pos.top-sizeY/2,wave.style.left=x+"px",wave.style.top=y+"px",this._center?wave.classList.add("ripple__wave--animate-center"):wave.classList.add("ripple__wave--animate")}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}}]),RippleElement}(ons._BaseElement);window.OnsRippleElement||(window.OnsRippleElement=document.registerElement("ons-ripple",{prototype:RippleElement.prototype}))}(),window.OnsRowElement=window.OnsRowElement?window.OnsRowElement:document.registerElement("ons-row"),window.OnsScrollerElement=window.OnsScrollerElement?window.OnsScrollerElement:document.registerElement("ons-scroller");var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial__item--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialItemElement=function(_ons$_BaseElement){function SpeedDialItemElement(){_classCallCheck(this,SpeedDialItemElement),_get(Object.getPrototypeOf(SpeedDialItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialItemElement,_ons$_BaseElement),_createClass(SpeedDialItemElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this.classList.add("fab--mini"),this.classList.add("speed-dial__item"),this._boundOnClick=this._onClick.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){e.stopPropagation()}}]),SpeedDialItemElement}(ons._BaseElement);window.OnsSpeedDialItemElement||(window.OnsSpeedDialItemElement=document.registerElement("ons-speed-dial-item",{prototype:SpeedDialItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialElement=function(_ons$_BaseElement){function SpeedDialElement(){_classCallCheck(this,SpeedDialElement),_get(Object.getPrototypeOf(SpeedDialElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialElement,_ons$_BaseElement),_createClass(SpeedDialElement,[{key:"createdCallback",value:function(){this._compile(),this._shown=!0,this._itemShown=!1,ModifierUtil.initModifier(this,scheme),this._boundOnClick=this._onClick.bind(this),this.classList.add("speed__dial"),this.hasAttribute("direction")?this._updateDirection(this.getAttribute("direction")):this._updateDirection("up"),this._updatePosition(),this.hasAttribute("disabled")&&this.setDisabled(!0)}},{key:"_compile",value:function(){var content=document.createElement("ons-fab");ons._util.arrayFrom(this.childNodes).forEach(function(element){return"ons-speed-dial-item"!==element.nodeName.toLowerCase()?content.firstChild.appendChild(element):!0});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._updateDirection(current):"position"===name?this._updatePosition():"disabled"===name&&(null!==current?this.setDisabled(!0):this.setDisabled(!1)))}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){this.isDisabled()||this.toggleItems()}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updateDirection",value:function(direction){for(var children=this.items,i=0;i<children.length;i++)children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms",children[i].style.bottom="auto",children[i].style.right="auto",children[i].style.top="auto",children[i].style.left="auto";switch(direction){case"up":for(var i=0;i<children.length;i++)children[i].style.bottom=72+56*i+"px",children[i].style.right="8px";break;case"down":for(var i=0;i<children.length;i++)children[i].style.top=72+56*i+"px",children[i].style.left="8px";break;case"left":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.right=72+56*i+"px";break;case"right":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.left=72+56*i+"px";break;default:throw new Error("Argument must be one of up, down, left or right.")}}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.querySelector("ons-fab").show(),this._shown=!0}},{key:"hide",value:function(){var _this=this;arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.hideItems(),setTimeout(function(){_this.querySelector("ons-fab").hide()},200),this._shown=!1}},{key:"showItems",value:function(){if(!this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(1)",children[i].style.webkitTransform="scale(1)",children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms";this._itemShown=!0}},{key:"hideItems",value:function(){if(this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(0)",children[i].style.webkitTransform="scale(0)",children[i].style.transitionDelay=25*(children.length-i)+"ms",children[i].style.webkitTransitionDelay=25*(children.length-i)+"ms";this._itemShown=!1}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?(this.hideItems(),this.setAttribute("disabled",""),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.setAttribute("disabled",""):!0})):(this.removeAttribute("disabled"),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.removeAttribute("disabled"):!0}))}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return this._shown&&"none"!==this.style.display}},{key:"isItemShown",value:function(){return this._itemShown}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}},{key:"toggleItems",value:function(){this.isItemShown()?this.hideItems():this.showItems()}},{key:"items",get:function(){return ons._util.arrayFrom(this.querySelectorAll("ons-speed-dial-item"))}}]),SpeedDialElement}(ons._BaseElement);window.OnsSpeedDialElement||(window.OnsSpeedDialElement=document.registerElement("ons-speed-dial",{prototype:SpeedDialElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},SplitterContentElement=function(_ons$_BaseElement){function SplitterContentElement(){_classCallCheck(this,SplitterContentElement),_get(Object.getPrototypeOf(SplitterContentElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterContentElement,_ons$_BaseElement),_createClass(SplitterContentElement,[{key:"createdCallback",value:function(){this._page=null}},{key:"load",value:function(page){var _this=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this,util.createFragment(html),function(fragment){for(;_this.childNodes[0];)_this.childNodes[0]._hide instanceof Function&&_this.childNodes[0]._hide(),_this.removeChild(_this.childNodes[0]);_this.appendChild(fragment),util.arrayFrom(fragment.children).forEach(function(child){child._show instanceof Function&&child._show()}),options.callback()})})}},{key:"attachedCallback",value:function(){var _this2=this;this._assertParent(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this2,function(){return _this2.load(_this2.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"page",get:function(){return this._page}}]),SplitterContentElement}(ons._BaseElement);window.OnsSplitterContentElement||(window.OnsSplitterContentElement=document.registerElement("ons-splitter-content",{prototype:SplitterContentElement.prototype}),window.OnsSplitterContentElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var SplitterMaskElement=function(_ons$_BaseElement){function SplitterMaskElement(){_classCallCheck(this,SplitterMaskElement),_get(Object.getPrototypeOf(SplitterMaskElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterMaskElement,_ons$_BaseElement),_createClass(SplitterMaskElement,[{key:"createdCallback",value:function(){this._boundOnClick=this._onClick.bind(this)}},{key:"_onClick",value:function(event){this.parentElement&&"ons-splitter"===this.parentElement.nodeName.toLowerCase()&&(this.parentElement.closeRight(),this.parentElement.closeLeft()),event.stopPropagation()}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick);
}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick)}}]),SplitterMaskElement}(ons._BaseElement);window.OnsSplitterMaskElement||(window.OnsSplitterMaskElement=document.registerElement("ons-splitter-mask",{prototype:SplitterMaskElement.prototype}))}();var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_get=function(_x9,_x10,_x11){for(var _again=!0;_again;){var object=_x9,property=_x10,receiver=_x11;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x9=parent,_x10=property,_x11=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(){"use strict";var util=ons._util,AnimatorFactory=ons._internal.AnimatorFactory,SPLIT_MODE="split",COLLAPSE_MODE="collapse",CollapseDetection=function(){function CollapseDetection(){_classCallCheck(this,CollapseDetection)}return _createClass(CollapseDetection,[{key:"activate",value:function(element){}},{key:"inactivate",value:function(){}}]),CollapseDetection}(),rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},OrientationCollapseDetection=function(_CollapseDetection){function OrientationCollapseDetection(orientation){if(_classCallCheck(this,OrientationCollapseDetection),_get(Object.getPrototypeOf(OrientationCollapseDetection.prototype),"constructor",this).call(this),"portrait"!==orientation&&"landscape"!==orientation)throw new Error("Invalid orientation: "+orientation);this._boundOnOrientationChange=this._onOrientationChange.bind(this),this._targetOrientation=orientation}return _inherits(OrientationCollapseDetection,_CollapseDetection),_createClass(OrientationCollapseDetection,[{key:"activate",value:function(element){this._element=element,ons.orientation.on("change",this._boundOnOrientationChange),this._update(ons.orientation.isPortrait())}},{key:"_onOrientationChange",value:function(info){this._update(info.isPortrait)}},{key:"_update",value:function(isPortrait){isPortrait&&"portrait"===this._targetOrientation?this._element._updateMode(COLLAPSE_MODE):isPortrait||"landscape"!==this._targetOrientation?this._element._updateMode(SPLIT_MODE):this._element._updateMode(COLLAPSE_MODE)}},{key:"inactivate",value:function(){this._element=null,ons.orientation.off("change",this._boundOnOrientationChange)}}]),OrientationCollapseDetection}(CollapseDetection),StaticCollapseDetection=function(_CollapseDetection2){function StaticCollapseDetection(){_classCallCheck(this,StaticCollapseDetection),_get(Object.getPrototypeOf(StaticCollapseDetection.prototype),"constructor",this).apply(this,arguments)}return _inherits(StaticCollapseDetection,_CollapseDetection2),_createClass(StaticCollapseDetection,[{key:"activate",value:function(element){element._updateMode(COLLAPSE_MODE)}}]),StaticCollapseDetection}(CollapseDetection),MediaQueryCollapseDetection=function(_CollapseDetection3){function MediaQueryCollapseDetection(query){_classCallCheck(this,MediaQueryCollapseDetection),_get(Object.getPrototypeOf(MediaQueryCollapseDetection.prototype),"constructor",this).call(this),this._mediaQueryString=query,this._boundOnChange=this._onChange.bind(this)}return _inherits(MediaQueryCollapseDetection,_CollapseDetection3),_createClass(MediaQueryCollapseDetection,[{key:"_onChange",value:function(queryList){this._element._updateMode(queryList.matches?COLLAPSE_MODE:SPLIT_MODE)}},{key:"activate",value:function(element){this._element=element,this._queryResult=window.matchMedia(this._mediaQueryString),this._queryResult.addListener(this._boundOnChange),this._onChange(this._queryResult)}},{key:"inactivate",value:function(){this._element=null,this._queryResult.removeListener(this._boundOnChange),this._queryResult=null}}]),MediaQueryCollapseDetection}(CollapseDetection),BaseMode=function(){function BaseMode(){_classCallCheck(this,BaseMode)}return _createClass(BaseMode,[{key:"isOpened",value:function(){return!1}},{key:"openMenu",value:function(){return!1}},{key:"closeMenu",value:function(){return!1}},{key:"enterMode",value:function(){}},{key:"exitMode",value:function(){}},{key:"handleGesture",value:function(){}}]),BaseMode}(),SplitMode=function(_BaseMode){function SplitMode(element){_classCallCheck(this,SplitMode),_get(Object.getPrototypeOf(SplitMode.prototype),"constructor",this).call(this),this._element=element}return _inherits(SplitMode,_BaseMode),_createClass(SplitMode,[{key:"isOpened",value:function(){return!1}},{key:"layout",value:function(){var element=this._element;element.style.width=element._getWidth(),element._isLeftSide()?(element.style.left="0",element.style.right="auto"):(element.style.left="auto",element.style.right="0")}},{key:"enterMode",value:function(){this.layout()}},{key:"exitMode",value:function(){var element=this._element;element.style.left="",element.style.right="",element.style.width="",element.style.zIndex=""}}]),SplitMode}(BaseMode),CollapseMode=function(_BaseMode2){function CollapseMode(element){_classCallCheck(this,CollapseMode),_get(Object.getPrototypeOf(CollapseMode.prototype),"constructor",this).call(this),this._state=CollapseMode.CLOSED_STATE,this._distance=0,this._element=element,this._lock=new DoorLock}return _inherits(CollapseMode,_BaseMode2),_createClass(CollapseMode,[{key:"_animator",get:function(){return this._element._getAnimator()}}],[{key:"CLOSED_STATE",get:function(){return"closed"}},{key:"OPENED_STATE",get:function(){return"opened"}},{key:"CHANGING_STATE",get:function(){return"changing"}}]),_createClass(CollapseMode,[{key:"_isLocked",value:function(){return this._lock.isLocked()}},{key:"isOpened",value:function(){return this._state!==CollapseMode.CLOSED_STATE}},{key:"isClosed",value:function(){return this._state===CollapseMode.CLOSED_STATE}},{key:"handleGesture",value:function(event){if(!this._isLocked()&&!this._openedOtherSideMenu())if("dragstart"===event.type)this._onDragStart(event);else if("dragleft"===event.type||"dragright"===event.type)this._ignoreDrag||this._onDrag(event);else{if("dragend"!==event.type)throw new Error("Invalid state");this._ignoreDrag||this._onDragEnd(event)}}},{key:"_onDragStart",value:function(event){if(this._ignoreDrag=!1,!this.isOpened()&&this._openedOtherSideMenu())this._ignoreDrag=!0;else if(this._element._swipeTargetWidth>0){var distance=this._element._isLeftSide()?event.gesture.center.clientX:window.innerWidth-event.gesture.center.clientX;distance>this._element._swipeTargetWidth&&(this._ignoreDrag=!0)}}},{key:"_onDrag",value:function(event){event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,startEvent=event.gesture.startEvent;"isOpened"in startEvent||(startEvent.isOpened=this.isOpened(),startEvent.distance=startEvent.isOpened?this._element._getWidthInPixel():0,startEvent.width=this._element._getWidthInPixel());var width=this._element._getWidthInPixel();if(!(0>deltaDistance&&startEvent.distance<=0||deltaDistance>0&&startEvent.distance>=width)){var distance=startEvent.isOpened?deltaDistance+width:deltaDistance,normalizedDistance=Math.max(0,Math.min(width,distance));startEvent.distance=normalizedDistance,this._state=CollapseMode.CHANGING_STATE,this._animator.translate(normalizedDistance)}}},{key:"_onDragEnd",value:function(event){var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,width=event.gesture.startEvent.width,distance=event.gesture.startEvent.isOpened?deltaDistance+width:deltaDistance,direction=event.gesture.interimDirection,shouldOpen=this._element._isLeftSide()&&"right"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen()||!this._element._isLeftSide()&&"left"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen();shouldOpen?this._openMenu():this._closeMenu()}},{key:"layout",value:function(){if(this._state!==CollapseMode.CHANGING_STATE)if(this._state===CollapseMode.CLOSED_STATE)this._animator.isActivated()&&this._animator.layoutOnClose();else{if(this._state!==CollapseMode.OPENED_STATE)throw new Error("Invalid state");this._animator.isActivated()&&this._animator.layoutOnOpen()}}},{key:"enterMode",value:function(){this._animator.activate(this._element._getContentElement(),this._element,this._element._getMaskElement()),this.layout()}},{key:"exitMode",value:function(){this._animator.inactivate()}},{key:"_openedOtherSideMenu",value:function(){var _this=this;return util.arrayFrom(this._element.parentElement.children).filter(function(child){return"ons-splitter-side"===child.nodeName.toLowerCase()&&_this._element!==child}).filter(function(side){return side.isOpened()}).length>0}},{key:"openMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.CLOSED_STATE?!1:this._openMenu(options)}},{key:"_openMenu",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._openedOtherSideMenu())return!1;if(this._element._emitPreOpenEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this2._element._emitPostOpenEvent(),options.callback()};return options.withoutAnimation?(this._state=CollapseMode.OPENED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.open(function(){_this2._state=CollapseMode.OPENED_STATE,_this2.layout(),done()})),!0}},{key:"closeMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.OPENED_STATE?!1:this._closeMenu(options)}},{key:"_closeMenu",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._element._emitPreCloseEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this3._element._emitPostCloseEvent(),setImmediate(options.callback)};return options.withoutAnimation?(this._state=CollapseMode.CLOSED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.close(function(){_this3._state=CollapseMode.CLOSED_STATE,_this3.layout(),done()})),!0}}]),CollapseMode}(BaseMode),SplitterSideElement=function(_ons$_BaseElement){function SplitterSideElement(){_classCallCheck(this,SplitterSideElement),_get(Object.getPrototypeOf(SplitterSideElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterSideElement,_ons$_BaseElement),_createClass(SplitterSideElement,[{key:"_updateForAnimationOptionsAttribute",value:function(){this._animationOptions=util.parseJSONObjectSafely(this.getAttribute("animation-options"),{})}},{key:"_getMaskElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-mask")}},{key:"_getContentElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-content")}},{key:"_getModeStrategy",value:function(){return this._mode===COLLAPSE_MODE?this._collapseMode:this._mode===SPLIT_MODE?this._splitMode:void 0}},{key:"createdCallback",value:function(){this._mode=null,this._page=null,this._isAttached=!1,this._collapseStrategy=new CollapseDetection,this._animatorFactory=new AnimatorFactory({animators:window.OnsSplitterElement._animatorDict,baseClass:ons._internal.SplitterAnimator,baseClassName:"SplitterAnimator",defaultAnimation:this.getAttribute("animation")}),this._collapseMode=new CollapseMode(this),this._splitMode=new SplitMode(this),this._boundHandleGesture=this._handleGesture.bind(this),this._cancelModeDetection=function(){},this._updateMode(SPLIT_MODE),this._updateForAnimationAttribute(),this._updateForWidthAttribute(),this._updateForSideAttribute(),this._updateForCollapseAttribute(),this._updateForSwipeableAttribute(),this._updateForSwipeTargetWidthAttribute(),this._updateForAnimationOptionsAttribute()}},{key:"_getAnimator",value:function(){return this._animator}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"_emitPostOpenEvent",value:function(){util.triggerElementEvent(this,"postopen",{side:this})}},{key:"_emitPostCloseEvent",value:function(){util.triggerElementEvent(this,"postclose",{side:this})}},{key:"_emitPreOpenEvent",value:function(){return this._emitCancelableEvent("preopen")}},{key:"_emitCancelableEvent",value:function(name){var isCanceled=!1;return util.triggerElementEvent(this,name,{side:this,cancel:function(){return isCanceled=!0}}),isCanceled}},{key:"_emitPreCloseEvent",value:function(){return this._emitCancelableEvent("preclose")}},{key:"_updateForCollapseAttribute",value:function(){if(!this.hasAttribute("collapse"))return void this._updateMode(SPLIT_MODE);var collapse=(""+this.getAttribute("collapse")).trim();""===collapse?this._updateCollapseStrategy(new StaticCollapseDetection):"portrait"===collapse||"landscape"===collapse?this._updateCollapseStrategy(new OrientationCollapseDetection(collapse)):this._updateCollapseStrategy(new MediaQueryCollapseDetection(collapse))}},{key:"_updateCollapseStrategy",value:function(strategy){this._isAttached&&(this._collapseStrategy.inactivate(),strategy.activate(this)),this._collapseStrategy=strategy}},{key:"_updateMode",value:function(mode){if(mode!==COLLAPSE_MODE&&mode!==SPLIT_MODE)throw new Error("invalid mode: "+mode);if(mode!==this._mode){var lastMode=this._getModeStrategy();lastMode&&lastMode.exitMode(),this._mode=mode;var currentMode=this._getModeStrategy();currentMode.enterMode(),this.setAttribute("mode",mode),util.triggerElementEvent(this,"modechange",{side:this,mode:mode})}}},{key:"_getThresholdRatioIfShouldOpen",value:function(){if(this.hasAttribute("threshold-ratio-should-open")){var value=parseFloat(this.getAttribute("threshold-ratio-should-open"));return Math.max(0,Math.min(1,value))}return.3}},{key:"_layout",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSwipeTargetWidthAttribute",value:function(){this.hasAttribute("swipe-target-width")?this._swipeTargetWidth=Math.max(0,parseInt(this.getAttribute("swipe-target-width"),10)):this._swipeTargetWidth=-1}},{key:"_getWidth",value:function(){function normalize(width){return width=width.trim(),width.match(/^\d+(px|%)$/)?width:"80%"}return this.hasAttribute("width")?normalize(this.getAttribute("width")):"80%"}},{key:"_getWidthInPixel",value:function(){var width=this._getWidth(),_width$match=width.match(/^(\d+)(px|%)$/),_width$match2=_slicedToArray(_width$match,3),num=_width$match2[1],unit=_width$match2[2];if("px"===unit)return parseInt(num,10);if("%"===unit){var percent=parseInt(num,10);return Math.round(this.parentElement.offsetWidth*percent/100)}throw new Error("Invalid state")}},{key:"_getSide",value:function(){function normalize(side){return side=(""+side).trim(),"left"===side||"right"===side?side:"left"}return normalize(this.getAttribute("side"))}},{key:"_isLeftSide",value:function(){return"left"===this._getSide()}},{key:"_updateForWidthAttribute",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSideAttribute",value:function(){this._getModeStrategy().layout()}},{key:"getCurrentMode",value:function(){return this._mode}},{key:"isOpened",value:function(){return this._getModeStrategy().isOpened()}},{key:"open",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().openMenu(options)}},{key:"close",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().closeMenu(options)}},{key:"load",value:function(page){var _this4=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this4,util.createFragment(html),function(fragment){for(;_this4.childNodes[0];)_this4.childNodes[0]._hide instanceof Function&&_this4.childNodes[0]._hide(),_this4.removeChild(_this4.childNodes[0]);_this4.appendChild(fragment),util.arrayFrom(fragment.childNodes).forEach(function(node){node._show instanceof Function&&node._show()}),options.callback()})})}},{key:"toggle",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this.isOpened()?this.close(options):this.open(options)}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name?this._updateForWidthAttribute():"side"===name?this._updateForSideAttribute():"collapse"===name?this._updateForCollapseAttribute():"swipeable"===name?this._updateForSwipeableAttribute():"swipe-target-width"===name?this._updateForSwipeTargetWidthAttribute():"animation-options"===name?this._updateForAnimationOptionsAttribute():"animation"===name&&this._updateForAnimationAttribute()}},{key:"_updateForAnimationAttribute",value:function(){var isActivated=this._animator&&this._animator.isActivated();isActivated&&this._animator.inactivate(),this._animator=this._createAnimator(),isActivated&&this._animator.activate(this._getContentElement(),this,this._getMaskElement())}},{key:"_updateForSwipeableAttribute",value:function(){this._gestureDetector&&(this.isSwipeable()?this._gestureDetector.on("dragstart dragleft dragright dragend",this._boundHandleGesture):this._gestureDetector.off("dragstart dragleft dragright dragend",this._boundHandleGesture))}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"attachedCallback",value:function(){var _this5=this;this._isAttached=!0,this._collapseStrategy.activate(this),this._assertParent(),this._gestureDetector=new ons.GestureDetector(this.parentElement,{dragMinDistance:1}),this._updateForSwipeableAttribute(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this5,function(){return _this5.load(_this5.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){this._isAttached=!1,this._collapseStrategy.inactivate(),this._gestureDetector.dispose(),this._gestureDetector=null,this._updateForSwipeableAttribute()}},{key:"_handleGesture",value:function(event){return this._getModeStrategy().handleGesture(event)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_createAnimator",value:function(){return this._animatorFactory.newAnimator({animation:this.getAttribute("animation"),animationOptions:AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))})}},{key:"page",get:function(){return this._page}},{key:"mode",get:function(){this._mode}}]),SplitterSideElement}(ons._BaseElement);window.OnsSplitterSideElement||(window.OnsSplitterSideElement=document.registerElement("ons-splitter-side",{prototype:SplitterSideElement.prototype}),window.OnsSplitterSideElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"switch--*",".switch__input":"switch--*__input",".switch__toggle":"switch--*__toggle"},ModifierUtil=ons._internal.ModifierUtil,templateSource=ons._util.createElement('\n <div>\n <input type="checkbox" class="switch__input">\n <div class="switch__toggle"></div>\n </div>\n '),ExtendableLabelElement=void 0;"function"!=typeof HTMLLabelElement?(ExtendableLabelElement=function(){},ExtendableLabelElement.prototype=document.createElement("label")):ExtendableLabelElement=HTMLLabelElement;var generateId=function(){var i=0;return function(){return"ons-switch-id-"+i++}}(),SwitchElement=function(_ExtendableLabelElement){function SwitchElement(){_classCallCheck(this,SwitchElement),_get(Object.getPrototypeOf(SwitchElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SwitchElement,_ExtendableLabelElement),_createClass(SwitchElement,[{key:"isChecked",value:function(){return this.checked}},{key:"setChecked",value:function(isChecked){this.checked=!!isChecked}},{key:"getCheckboxElement",value:function(){return this._getCheckbox()}},{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateForCheckedAttribute(),this._updateForDisabledAttribute()}},{key:"_updateForCheckedAttribute",value:function(){this.hasAttribute("checked")?this._getCheckbox().checked=!0:this._getCheckbox().checked=!1}},{key:"_updateForDisabledAttribute",value:function(){this.hasAttribute("disabled")?this._getCheckbox().setAttribute("disabled",""):this._getCheckbox().removeAttribute("disabled")}},{key:"_compile",value:function(){this.classList.add("switch");for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this._getCheckbox().setAttribute("name",generateId())}},{key:"detachedCallback",value:function(){this._getCheckbox().removeEventListener("change",this._onChangeListener)}},{key:"attachedCallback",value:function(){this._getCheckbox().addEventListener("change",this._onChangeListener)}},{key:"_onChangeListener",value:function(){this.checked!==!0?this.removeAttribute("checked"):this.setAttribute("checked","")}},{key:"_isChecked",value:function(){return this._getCheckbox().checked}},{key:"_setChecked",value:function(isChecked){isChecked=!!isChecked;var checkbox=this._getCheckbox();checkbox.checked!=isChecked&&(checkbox.checked=isChecked)}},{key:"_getCheckbox",value:function(){return this.querySelector("input[type=checkbox]")}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("checked"===name?this._updateForCheckedAttribute():"disabled"===name&&this._updateForDisabledAttribute())}},{key:"checked",get:function(){return this._getCheckbox().checked},set:function(value){this._getCheckbox().checked=value,this.checked?this.setAttribute("checked",""):this.removeAttribute("checked"),this._updateForCheckedAttribute()}},{key:"disabled",get:function(){return this._getCheckbox().disabled},set:function(value){this._getCheckbox().disabled=value,this.disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}}]),SwitchElement}(ExtendableLabelElement);window.OnsSwitchElement||(window.OnsSwitchElement=document.registerElement("ons-switch",{prototype:SwitchElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".tab-bar__content":"tab-bar--*__content",".tab-bar":"tab-bar--*"},AnimatorFactory=ons._internal.AnimatorFactory,TabbarAnimator=ons._internal.TabbarAnimator,TabbarFadeAnimator=ons._internal.TabbarFadeAnimator,TabbarNoneAnimator=ons._internal.TabbarNoneAnimator,TabbarSlideAnimator=ons._internal.TabbarSlideAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":TabbarNoneAnimator,fade:TabbarFadeAnimator,slide:TabbarSlideAnimator,none:TabbarNoneAnimator},rewritables={ready:function(tabbarElement,callback){callback()},link:function(tabbarElement,target,callback){callback(target)},unlink:function(tabbarElement,target,callback){callback(target)}},generateId=function(){var i=0;return function(){return"ons-tabbar-gen-"+i++}}(),TabbarElement=function(_ons$_BaseElement){function TabbarElement(){_classCallCheck(this,TabbarElement),_get(Object.getPrototypeOf(TabbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarElement,_ons$_BaseElement),_createClass(TabbarElement,[{key:"createdCallback",value:function(){this._tabbarId=generateId(),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:TabbarAnimator,baseClassName:"TabbarAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),this._contentElement=ons._util.findChild(this,".tab-bar__content"),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var wrapper=document.createDocumentFragment(),content=document.createElement("div");content.classList.add("ons-tab-bar__content"),content.classList.add("tab-bar__content");var tabbar=document.createElement("div");for(tabbar.classList.add("tab-bar"),tabbar.classList.add("ons-tab-bar__footer"),tabbar.classList.add("ons-tabbar-inner"),wrapper.appendChild(content),wrapper.appendChild(tabbar);this.childNodes[0];)tabbar.appendChild(this.removeChild(this.childNodes[0]));this.appendChild(wrapper),this._hasTopTabbar()&&this._prepareForTopTabbar()}},{key:"_hasTopTabbar",value:function(){return"top"===this.getAttribute("position")}},{key:"_prepareForTopTabbar",value:function(){var content=ons._util.findChild(this,".tab-bar__content"),tabbar=ons._util.findChild(this,".tab-bar");content.setAttribute("no-status-bar-fill",""),content.classList.add("tab-bar--top__content"),tabbar.classList.add("tab-bar--top");var page=ons._util.findParent(this,"ons-page");if(page&&(this.style.top=window.getComputedStyle(page._getContentElement(),null).getPropertyValue("padding-top")),ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("tab-bar__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_getTabbarElement",value:function(){return util.findChild(this,".tab-bar")}},{key:"loadPage",value:function(page,options){return options=options||{},options._removeElement=!0,this._loadPage(page,options)}},{key:"_loadPage",value:function(page,options){var _this=this;OnsTabElement.prototype._createPageElement(page,function(pageElement){_this._loadPageDOMAsync(pageElement,options)})}},{key:"_loadPageDOMAsync",value:function(pageElement,options){var _this2=this;options=options||{},rewritables.link(this,pageElement,function(pageElement){_this2._contentElement.appendChild(pageElement),_this2._switchPage(pageElement,options)})}},{key:"getTabbarId",value:function(){return this._tabbarId}},{key:"_getCurrentPageElement",value:function(){for(var pages=this._contentElement.children,page=null,i=0;i<pages.length;i++)if("none"!==pages[i].style.display){page=pages[i];break}if(page&&"ons-page"!==page.nodeName.toLowerCase())throw new Error('Invalid state: page element must be a "ons-page" element.');return page}},{key:"_switchPage",value:function(element,options){if(-1!==this.getActiveTabIndex()){var oldPageElement=this._oldPageElement||ons._internal.nullElement;this._oldPageElement=element;var animator=this._animatorFactory.newAnimator(options);animator.apply(element,oldPageElement,options.selectedTabIndex,options.previousTabIndex,function(){oldPageElement!==ons._internal.nullElement&&(options._removeElement?rewritables.unlink(this,oldPageElement,function(pageElement){oldPageElement._destroy()}):(oldPageElement.style.display="none",oldPageElement._hide())),element.style.display="block",element._show(),options.callback instanceof Function&&options.callback()})}else options.callback instanceof Function&&options.callback()}},{key:"setActiveTab",value:function(index,options){var _this3=this;options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var previousTab=this._getActiveTabElement(),selectedTab=this._getTabElement(index),previousTabIndex=this.getActiveTabIndex(),selectedTabIndex=index;if(!selectedTab)return!1;if((selectedTab.hasAttribute("no-reload")||selectedTab.isPersistent())&&index===previousTabIndex)return util.triggerElementEvent(this,"reactive",{index:index,tabItem:selectedTab}),!1;var canceled=!1;if(util.triggerElementEvent(this,"prechange",{index:index,tabItem:selectedTab,cancel:function(){return canceled=!0}}),canceled)return selectedTab.setInactive(),previousTab&&previousTab.setActive(),!1;selectedTab.setActive();var needLoad=!selectedTab.isLoaded()&&!options.keepPage;if(needLoad){var removeElement=!0;previousTab&&previousTab.isPersistent()&&(removeElement=!1);var params={callback:function(){util.triggerElementEvent(_this3,"postchange",{index:index,tabItem:selectedTab}),options.callback instanceof Function&&options.callback()},previousTabIndex:previousTabIndex,selectedTabIndex:selectedTabIndex,_removeElement:removeElement};if(options.animation&&(params.animation=options.animation),selectedTab.isPersistent()){var link=function(element,callback){rewritables.link(_this3,element,callback)};selectedTab._loadPageElement(function(pageElement){_this3._loadPersistentPageDOM(pageElement,params)},link)}else this._loadPage(selectedTab.getAttribute("page"),params)}return util.arrayFrom(this._getTabbarElement().children).forEach(function(tab){tab!=selectedTab?tab.setInactive():needLoad||util.triggerElementEvent(_this3,"postchange",{
index:index,tabItem:selectedTab})}),!0}},{key:"_loadPersistentPageDOM",value:function(element,options){options=options||{},util.isAttached(element)||this._contentElement.appendChild(element),this._switchPage(element,options)}},{key:"setTabbarVisibility",value:function(visible){this._contentElement.style[this._hasTopTabbar()?"top":"bottom"]=visible?"":"0px",this._getTabbarElement().style.display=visible?"":"none"}},{key:"getActiveTabIndex",value:function(){for(var tabs=this._getTabbarElement().children,i=0;i<tabs.length;i++)if(tabs[i]instanceof window.OnsTabElement&&tabs[i].isActive&&tabs[i].isActive())return i;return-1}},{key:"_getActiveTabElement",value:function(){return this._getTabElement(this.getActiveTabIndex())}},{key:"_getTabElement",value:function(index){return this._getTabbarElement().children[index]}},{key:"detachedCallback",value:function(){}},{key:"attachedCallback",value:function(){}},{key:"_show",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&¤tPageElement._show()}},{key:"_hide",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&¤tPageElement._hide()}},{key:"_destroy",value:function(){for(var pages=this._contentElement.children,i=pages.length-1;i>=0;i--)pages[i]._destroy();this.remove()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabbarElement}(ons._BaseElement);window.OnsTabbarElement||(window.OnsTabbarElement=document.registerElement("ons-tabbar",{prototype:TabbarElement.prototype}),window.OnsTabbarElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof TabbarAnimator))throw new Error('"Animator" param must inherit TabbarAnimator');_animatorDict[name]=Animator},window.OnsTabbarElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var TemplateElement=function(_ons$_BaseElement){function TemplateElement(){_classCallCheck(this,TemplateElement),_get(Object.getPrototypeOf(TemplateElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TemplateElement,_ons$_BaseElement),_createClass(TemplateElement,[{key:"createdCallback",value:function(){for(this.template=this.innerHTML;this.firstChild;)this.removeChild(this.firstChild)}},{key:"attachedCallback",value:function(){var event=new CustomEvent("_templateloaded",{bubbles:!0,cancelable:!0});event.template=this.template,event.templateId=this.getAttribute("id"),this.dispatchEvent(event)}}]),TemplateElement}(ons._BaseElement);window.OnsTemplateElement||(window.OnsTemplateElement=document.registerElement("ons-template",{prototype:TemplateElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"toolbar-button--*"},ModifierUtil=ons._internal.ModifierUtil,ToolbarButtonElement=function(_ons$_BaseElement){function ToolbarButtonElement(){_classCallCheck(this,ToolbarButtonElement),_get(Object.getPrototypeOf(ToolbarButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarButtonElement,_ons$_BaseElement),_createClass(ToolbarButtonElement,[{key:"createdCallback",value:function(){this.classList.add("toolbar-button"),this.classList.add("navigation-bar__line-height"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ToolbarButtonElement}(ons._BaseElement);window.OnsToolbarButton||(window.OnsToolbarButton=document.registerElement("ons-toolbar-button",{prototype:ToolbarButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"navigation-bar--*",".navigation-bar__left":"navigation-bar--*__left",".navigation-bar__center":"navigation-bar--*__center",".navigation-bar__right":"navigation-bar--*__right"},ModifierUtil=ons._internal.ModifierUtil,ToolbarElement=function(_ons$_BaseElement){function ToolbarElement(){_classCallCheck(this,ToolbarElement),_get(Object.getPrototypeOf(ToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarElement,_ons$_BaseElement),_createClass(ToolbarElement,[{key:"createdCallback",value:function(){var _this=this;this._compile(),ModifierUtil.initModifier(this,scheme),this._tryToEnsureNodePosition(),setImmediate(function(){return _this._tryToEnsureNodePosition()})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){var _this2=this;this._tryToEnsureNodePosition(),setImmediate(function(){return _this2._tryToEnsureNodePosition()})}},{key:"_tryToEnsureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerToolbar(this)}}},{key:"_getToolbarLeftItemsElement",value:function(){return this.querySelector(".left")||ons._internal.nullElement}},{key:"_getToolbarCenterItemsElement",value:function(){return this.querySelector(".center")||ons._internal.nullElement}},{key:"_getToolbarRightItemsElement",value:function(){return this.querySelector(".right")||ons._internal.nullElement}},{key:"_getToolbarBackButtonLabelElement",value:function(){return this.querySelector("ons-back-button .back-button__label")||ons._internal.nullElement}},{key:"_compile",value:function(){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!this.hasAttribute("fixed-style"),inline=this.hasAttribute("inline");this.classList.add("navigation-bar"),shouldAppendAndroidModifier&&this.classList.add("navigation-bar--android"),inline||(this.style.position="absolute",this.style.zIndex="10000",this.style.left="0px",this.style.right="0px",this.style.top="0px"),this._ensureToolbarItemElements()}},{key:"_ensureToolbarItemElements",value:function(){for(var center,hasCenterClassElementOnly=1===this.children.length&&this.children[0].classList.contains("center"),i=0;i<this.childNodes.length;i++)1!=this.childNodes[i].nodeType&&this.removeChild(this.childNodes[i]);if(hasCenterClassElementOnly)center=this._ensureToolbarItemContainer("center");else{center=this._ensureToolbarItemContainer("center");var left=this._ensureToolbarItemContainer("left"),right=this._ensureToolbarItemContainer("right");if(this.children[0]!==left||this.children[1]!==center||this.children[2]!==right){left.parentNode&&this.removeChild(left),center.parentNode&&this.removeChild(center),right.parentNode&&this.removeChild(right);var fragment=document.createDocumentFragment();fragment.appendChild(left),fragment.appendChild(center),fragment.appendChild(right),this.appendChild(fragment)}}center.classList.add("navigation-bar__title")}},{key:"_ensureToolbarItemContainer",value:function(name){var container=ons._util.findChild(this,"."+name);return container||(container=document.createElement("div"),container.classList.add(name)),""===container.innerHTML.trim()&&(container.innerHTML=" "),container.classList.add("navigation-bar__"+name),container}}]),ToolbarElement}(ons._BaseElement);window.OnsToolbarElement||(window.OnsToolbarElement=document.registerElement("ons-toolbar",{prototype:ToolbarElement.prototype}))}(); |
docs/src/app/components/pages/components/Card/Page.js | ichiohta/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import cardReadmeText from './README';
import cardExampleWithAvatarCode from '!raw!./ExampleWithAvatar';
import CardExampleWithAvatar from './ExampleWithAvatar';
import cardExampleExpandableCode from '!raw!./ExampleExpandable';
import CardExampleExpandable from './ExampleExpandable';
import cardExampleControlledCode from '!raw!./ExampleControlled';
import CardExampleControlled from './ExampleControlled';
import cardCode from '!raw!material-ui/Card/Card';
import cardActionsCode from '!raw!material-ui/Card/CardActions';
import cardHeaderCode from '!raw!material-ui/Card/CardHeader';
import cardMediaCode from '!raw!material-ui/Card/CardMedia';
import cardTextCode from '!raw!material-ui/Card/CardText';
import cardTitleCode from '!raw!material-ui/Card/CardTitle';
const descriptions = {
avatar: 'A `Card` containing each of the card components: `CardHeader` (with avatar), `CardMedia` (with overlay), ' +
'`CardTitle`, `CardText` & `CardActions`.',
simple: 'An expandable `Card` with `CardHeader`, `CardText` and `CardActions`. ' +
'Use the icon to expand the card.',
controlled: 'A controlled expandable `Card`. Use the icon, the toggle or the ' +
'buttons to control the expanded state of the card.',
};
const CardPage = () => (
<div>
<Title render={(previousTitle) => `Card - ${previousTitle}`} />
<MarkdownElement text={cardReadmeText} />
<CodeExample
title="Card components example"
description={descriptions.avatar}
code={cardExampleWithAvatarCode}
>
<CardExampleWithAvatar />
</CodeExample>
<CodeExample
title="Expandable example"
description={descriptions.simple}
code={cardExampleExpandableCode}
>
<CardExampleExpandable />
</CodeExample>
<CodeExample
title="Controlled example"
description={descriptions.controlled}
code={cardExampleControlledCode}
>
<CardExampleControlled />
</CodeExample>
<PropTypeDescription code={cardCode} header="### Card properties" />
<PropTypeDescription code={cardActionsCode} header="### CardActions properties" />
<PropTypeDescription code={cardHeaderCode} header="### CardHeader properties" />
<PropTypeDescription code={cardMediaCode} header="### CardMedia properties" />
<PropTypeDescription code={cardTextCode} header="### CardText properties" />
<PropTypeDescription code={cardTitleCode} header="### CardTitle properties" />
</div>
);
export default CardPage;
|
molgenis-core-ui/src/main/javascript/modules/react-components/jobs/JobContainer.js | joerivandervelde/molgenis | /**
* The JobContainer retrieves progress for a single Job execution and renders it
* using the Job component.
*
* @module JobContainer
*
* @exports JobContainer factory
*/
import React from 'react';
import RestClient from "rest-client/RestClientV2";
import { Spinner } from '../Spinner'
import $ from 'jquery';
import { Job } from './Job';
import DeepPureRenderMixin from '../mixin/DeepPureRenderMixin';
import SetIntervalMixin from '../mixin/SetIntervalMixin';
var JobContainer = React.createClass({
mixins: [DeepPureRenderMixin, SetIntervalMixin],
displayName: 'JobContainer',
propTypes: {
jobHref: React.PropTypes.string,
onCompletion: React.PropTypes.func
},
getInitialState: function() {
return {
job : null
}
},
componentDidMount: function() {
this.retrieveJob();
this.setInterval(this.retrieveJob, 1000);
},
render: function() {
if(this.state.job) {
return <Job job={this.state.job}/>
} else {
return <Spinner />;
}
},
retrieveJob: function() {
var self = this;
$.get(this.props.jobHref, function(job) {
self.setState({job: job})
if((job.status === 'SUCCESS' || job.status === 'FAILED' || job.status === 'FINISHED') && self.props.onCompletion) {
self.props.onCompletion(job);
}
});
}
});
export { JobContainer };
export default React.createFactory(JobContainer); |
presentation/game/components/GridContainer.js | haampie/2048-react-slides | import React, { Component } from 'react';
export default class GridContainer extends Component {
render() {
return (
<div className="grid-container">
<div className="grid-row">
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
</div>
<div className="grid-row">
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
</div>
<div className="grid-row">
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
</div>
<div className="grid-row">
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
<div className="grid-cell"></div>
</div>
</div>
);
}
}
|
ajax/libs/forerunnerdb/1.3.659/fdb-all.min.js | keicheng/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/NodeApiClient"),a("../lib/BinaryLog");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":9,"../lib/Shim.IE8":41}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":34,"./Shared":40}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared"),j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){var b=this;b._logCounter=0,b._parent=a,b.size(1e3)},d.addModule("BinaryLog",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Events"),f=d.modules.Collection,h=d.modules.Db,e=d.modules.ReactorIO,g=f.prototype.init,i=h.prototype.init,d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"size"),j.prototype.attachIO=function(){var a=this;a._io||(a._log=new f(a._parent.name()+"-BinaryLog",{capped:!0,size:a.size()}),a._log.objectId=function(b){return b||(b=++a._logCounter),b},a._io=new e(a._parent,a,function(b){return a._log.insert({type:b.type,data:b.data}),!1}))},j.prototype.detachIO=function(){var a=this;a._io&&(a._log.drop(),a._io.drop(),delete a._log,delete a._io)},f.prototype.init=function(){g.apply(this,arguments),this._binaryLog=new j(this)},d.finishModule("BinaryLog"),b.exports=j},{"./Shared":40}],5:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":34,"./Shared":40}],6:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" 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",{dataSet:this.decouple(a),oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b(),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d(),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",{dataSet:this.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),
x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,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;case"2d":c=new k(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"}:(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()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":7,"./Shared":40}],9:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":7,"./Shared":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],13:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")
},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":32,"./Shared":40}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":5,"./Path":34,"./Shared":40}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":34,"./Shared":40}],18:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":40}],19:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":31,"./Shared":40}],20:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":32,"./Serialiser":39}],23:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":32}],25:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},
e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],27:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._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":32}],29:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i=a("./Shared");g=function(){this.init.apply(this,arguments)},g.prototype.init=function(a){var b=this;b._core=a,b.rootPath("/fdb")},i.addModule("NodeApiClient",g),i.mixin(g.prototype,"Mixin.Common"),i.mixin(g.prototype,"Mixin.Events"),i.mixin(g.prototype,"Mixin.ChainReactor"),d=i.modules.Core,e=d.prototype.init,f=i.modules.Collection,h=i.overload,i.synthesize(g.prototype,"rootPath"),g.prototype.server=function(a,b){return void 0!==a?("/"===a.substr(a.length-1,1)&&(a=a.substr(0,a.length-1)),void 0!==b?this._server=a+":"+b:this._server=a,this._host=a,this._port=b,this):void 0!==b?{host:this._host,port:this._port,url:this._server}:this._server},g.prototype.http=function(a,b,c,d,e){var f,g,h,i=this,j=new XMLHttpRequest;switch(a=a.toUpperCase(),j.onreadystatechange=function(){4===j.readyState&&(200===j.status?e(!1,i.jParse(j.responseText)):(e(j.status,j.responseText),i.emit("httpError",j.status,j.responseText)))},a){case"GET":case"DELETE":case"HEAD":this._sessionData&&(c=void 0!==c?c:{},c[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==c?"?"+i.jStringify(c):""),h=null;break;case"POST":case"PUT":case"PATCH":this._sessionData&&(g={},g[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==g?"?"+i.jStringify(g):""),h=void 0!==c?i.jStringify(c):null;break;default:return!1}return j.open(a,f,!0),j.setRequestHeader("Content-Type","application/json;charset=UTF-8"),j.send(h),this},g.prototype.head=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("HEAD",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.get=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("GET",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.put=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PUT",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.post=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("POST",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.patch=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PATCH",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.postPatch=function(a,b,c,d,e){var f=this;this.head(a+"/"+b,void 0,{},function(g,h){return g?404===g?f.http("POST",f.server()+f._rootPath+a,c,d,e):void e(g,c):f.http("PATCH",f.server()+f._rootPath+a+"/"+b,c,d,e)})},g.prototype["delete"]=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("DELETE",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.session=function(a,b){return void 0!==a&&void 0!==b?(this._sessionData={key:a,obj:b},this):this._sessionData},g.prototype.sync=function(a,b,c,d,e){var f,g,h,j=this,k="",l=!0;this.debug()&&console.log(this.logIdentifier()+" Connecting to API server "+this.server()+this._rootPath+b),g=this.server()+this._rootPath+b+"/_sync",this._sessionData&&(h=h||{},this._sessionData.key?h[this._sessionData.key]=this._sessionData.obj:i.mixin(h,this._sessionData.obj)),c&&(h=h||{},h.$query=c),d&&(h=h||{},void 0===d.$initialData&&(d.$initialData=!0),h.$options=d),h&&(k=this.jStringify(h),g+="?"+k),f=new EventSource(g),a.__apiConnection=f,f.addEventListener("open",function(c){(!d||d&&d.$initialData)&&j.get(b,h,function(b,c){b||a.upsert(c)})},!1),f.addEventListener("error",function(b){2===f.readyState&&a.unSync(),l&&(l=!1,e(b))},!1),f.addEventListener("insert",function(b){var c=j.jParse(b.data);a.insert(c.dataSet)},!1),f.addEventListener("update",function(b){var c=j.jParse(b.data);a.update(c.query,c.update)},!1),f.addEventListener("remove",function(b){var c=j.jParse(b.data);a.remove(c.query)},!1),e&&f.addEventListener("connected",function(a){l&&(l=!1,e(!1))},!1)},f.prototype.sync=new h({"function":function(a){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),null,null,a)},"string, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,null,null,b)},"object, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,null,b)},"string, string, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,null,null,c)},"string, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,null,c)},"string, string, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,null,d)},"object, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,b,c)},"string, object, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,c,d)},"string, string, object, object, function":function(a,b,c,d,e){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,d,e)},$main:function(a,b,c,d){var e=this;if(!this._db||!this._db._core)throw this.logIdentifier()+" Cannot sync for an anonymous collection! (Collection must be attached to a database)";this.unSync(),this._db._core.api.sync(this,a,b,c,d),this.on("drop",function(){e.unSync()})}}),f.prototype.unSync=function(){return this.__apiConnection?(2!==this.__apiConnection.readyState&&this.__apiConnection.close(),delete this.__apiConnection,!0):!1},f.prototype.http=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},$main:function(a,b,c,d,e,f){if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._rootPath+b,{$query:c,$options:d},e,f);throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),f.prototype.autoHttp=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},"string, string, function":function(a,b,c){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+b,void 0,void 0,{},c)},"string, string, string, function":function(a,b,c,d){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,void 0,void 0,{},d)},"string, string, string, object, function":function(a,b,c,d,e){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,void 0,{},e)},"string, string, string, object, object, function":function(a,b,c,d,e,f){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,e,{},f)},$main:function(a,b,c,d,e,f){var g=this;if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._db._core.api._rootPath+b,{$query:c,$options:d},e,function(b,c){var d;if(!b&&c)switch(a){case"GET":g.insert(c);break;case"POST":c.inserted&&c.inserted.length&&g.insert(c.inserted);break;case"PUT":case"PATCH":if(c instanceof Array)for(d=0;d<c.length;d++)g.updateById(c[d]._id,{$overwrite:c[d]});else g.updateById(c._id,{$overwrite:c});break;case"DELETE":g.remove(c)}f(b,c)});throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),d.prototype.init=function(){e.apply(this,arguments),this.api=new g(this)},i.finishModule("NodeApiClient"),b.exports=g},{"./Shared":40}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":34,"./Shared":40}],32:[function(a,b,c){"use strict";var d=function(a){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,g=[];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++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature "'+d+'" for the passed arguments: '+this.jStringify(g)}}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},{}],33:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":7,"./Document":11,"./Shared":40}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":40}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,
store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,async:43,localforage:79}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":40,pako:80}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":40,"crypto-js":52}],38:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":40}],39:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){if(a){var b,c=JSON.parse(a);for(b in this._decoder)if(this._decoder.hasOwnProperty(b)&&a.indexOf(b)>-1)return this._parse(c);return c}},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],40:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.659",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],42:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(){this._from.update.apply(this._from,arguments)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options)}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},o.prototype.query=new n({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor,this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){
a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:78}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":46}],46:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":46}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":46}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":45,"./core":46}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":46}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":46}],54:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":46}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":45,"./core":46}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":45,"./core":46}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":45,"./core":46}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":45,"./core":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":45,"./core":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":45,"./core":46}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":45,"./core":46}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":45,"./core":46}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":45,"./core":46}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":45,"./core":46}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];
this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":46}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":46}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":46,"./sha256":72}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":46}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":46,"./x64-core":77}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":46,"./x64-core":77}],76:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":46}],78:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],79:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2;
}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.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[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.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},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(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(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"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 w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.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=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.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,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.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=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.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&&(m.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;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.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 Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.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 Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.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&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(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 Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:78}],80:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":81,"./lib/inflate":82,"./lib/utils/common":83,"./lib/zlib/constants":86}],81:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":83,"./utils/strings":84,"./zlib/deflate.js":88,"./zlib/messages":93,"./zlib/zstream":95}],82:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":83,"./utils/strings":84,"./zlib/constants":86,"./zlib/gzheader":89,"./zlib/inflate.js":91,"./zlib/messages":93,"./zlib/zstream":95}],83:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],84:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;
for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":83}],85:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],86:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],87:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],88:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":83,"./adler32":85,"./crc32":87,"./messages":93,"./trees":94}],89:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],90:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],91:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":83,"./adler32":85,"./crc32":87,"./inffast":90,"./inftrees":92}],92:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":83}],93:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],94:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],
f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":83}],95:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]); |
packages/react-error-overlay/src/components/CodeBlock.js | johnslay/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import { redTransparent, yellowTransparent } from '../styles';
const _preStyle = {
display: 'block',
padding: '0.5em',
marginTop: '0.5em',
marginBottom: '0.5em',
overflowX: 'auto',
whiteSpace: 'pre-wrap',
borderRadius: '0.25rem',
};
const primaryPreStyle = {
..._preStyle,
backgroundColor: redTransparent,
};
const secondaryPreStyle = {
..._preStyle,
backgroundColor: yellowTransparent,
};
const codeStyle = {
fontFamily: 'Consolas, Menlo, monospace',
};
type CodeBlockPropsType = {|
main: boolean,
codeHTML: string,
|};
function CodeBlock(props: CodeBlockPropsType) {
const preStyle = props.main ? primaryPreStyle : secondaryPreStyle;
const codeBlock = { __html: props.codeHTML };
return (
<pre style={preStyle}>
<code style={codeStyle} dangerouslySetInnerHTML={codeBlock} />
</pre>
);
}
export default CodeBlock;
|
src/svg-icons/communication/live-help.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationLiveHelp = (props) => (
<SvgIcon {...props}>
<path d="M19 2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 16h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 11.9 13 12.5 13 14h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
</SvgIcon>
);
CommunicationLiveHelp = pure(CommunicationLiveHelp);
CommunicationLiveHelp.displayName = 'CommunicationLiveHelp';
CommunicationLiveHelp.muiName = 'SvgIcon';
export default CommunicationLiveHelp;
|
src/withSSR.js | i18next/react-i18next | import React from 'react';
import { useSSR } from './useSSR';
import { composeInitialProps } from './context';
import { getDisplayName } from './utils';
export function withSSR() {
return function Extend(WrappedComponent) {
function I18nextWithSSR({ initialI18nStore, initialLanguage, ...rest }) {
useSSR(initialI18nStore, initialLanguage);
return React.createElement(WrappedComponent, {
...rest,
});
}
I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;
I18nextWithSSR.WrappedComponent = WrappedComponent;
return I18nextWithSSR;
};
}
|
packages/cf-component-dropdown/src/Dropdown.js | mdno/mdno.github.io | import React from 'react';
import PropTypes from 'prop-types';
import { canUseDOM } from 'exenv';
import { createComponent } from 'cf-style-container';
import DropdownRegistry from './DropdownRegistry';
const styles = ({ theme, align }) => ({
position: 'absolute',
zIndex: 1,
minWidth: '10.66667rem',
margin: '0.5em 0 0',
padding: '0.33333rem 0',
listStyle: 'none',
background: theme.colorWhite,
border: `1px solid ${theme.colorGrayLight}`,
borderRadius: theme.borderRadius,
boxShadow: '0 3px 10px rgba(0, 0, 0, 0.2)',
left: align === 'left' ? 0 : 'initial',
right: align === 'right' ? 0 : 'initial',
textAlign: theme.textAlign,
animationName: {
'0%': {
display: 'none',
opacity: 0
},
'1%': {
display: 'block',
opacity: 0,
top: '80%'
},
'100%': {
display: 'none',
opacity: 1,
top: '102%'
}
},
animationDuration: '150ms',
animationTimingFunction: 'ease-out',
'&::before': {
content: "''",
display: 'block',
position: 'absolute',
bottom: '100%',
border: 'solid transparent',
borderWidth: '10px',
borderTopWidth: 0,
borderBottomColor: theme.colorWhite,
left: align === 'left' ? '10px' : 'initial',
right: align === 'right' ? '10px' : 'initial'
}
});
class Dropdown extends React.Component {
getChildContext() {
return {
dropdownRegistry: this.dropdownRegistry
};
}
constructor(props, context) {
super(props, context);
this.dropdownRegistry = new DropdownRegistry();
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.handleDocumentKeydown = this.handleDocumentKeydown.bind(this);
}
componentDidMount() {
if (canUseDOM) {
global.document.addEventListener('keydown', this.handleDocumentKeydown);
global.document.addEventListener('click', this.handleDocumentClick);
}
}
componentWillUnmount() {
if (canUseDOM) {
global.document.removeEventListener(
'keydown',
this.handleDocumentKeydown
);
global.document.removeEventListener('click', this.handleDocumentClick);
}
}
handleDocumentKeydown(event) {
const keyCode = event.keyCode;
if (keyCode === 40) {
// down
event.preventDefault();
this.dropdownRegistry.focusNext();
} else if (keyCode === 38) {
// up
event.preventDefault();
this.dropdownRegistry.focusPrev();
} else if (keyCode === 27) {
// esc
this.props.onClose();
}
}
handleDocumentClick() {
this.props.onClose();
}
render() {
return (
<ul className={this.props.className} role="menu">
{this.props.children}
</ul>
);
}
}
Dropdown.propTypes = {
onClose: PropTypes.func.isRequired,
align: PropTypes.oneOf(['left', 'right']),
children: PropTypes.node
};
Dropdown.defaultProps = {
align: 'left'
};
Dropdown.childContextTypes = {
dropdownRegistry: PropTypes.instanceOf(DropdownRegistry).isRequired
};
export default createComponent(styles, Dropdown);
|
src/svg-icons/maps/rate-review.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsRateReview = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 14v-2.47l6.88-6.88c.2-.2.51-.2.71 0l1.77 1.77c.2.2.2.51 0 .71L8.47 14H6zm12 0h-7.5l2-2H18v2z"/>
</SvgIcon>
);
MapsRateReview = pure(MapsRateReview);
MapsRateReview.displayName = 'MapsRateReview';
MapsRateReview.muiName = 'SvgIcon';
export default MapsRateReview;
|
ajax/libs/forerunnerdb/1.3.34/fdb-core.js | froala/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":3,"../lib/Shim.IE8":23}],2:[function(_dereq_,module,exports){
"use strict";
/**
* The main collection class. Collections store multiple documents and
* can operate on them using the query language to insert, read, update
* and delete.
*/
var Shared,
Core,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Collection object used to store data.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._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
};
// Set the subset to itself since it is the root collection
this._subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Core = Shared.modules.Core;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Get the internal data
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function () {
var key;
if (this._state !== 'dropped') {
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];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
}
}
return this.$super.apply(this, arguments);
});
/**
* Sets the collection's data to the array of documents passed.
* @param data
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw('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: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log('Updating some collection data for collection "' + this.name() + '"');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (originalDoc) {
var newDoc = self.decouple(originalDoc),
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, update, query, options, '');
}
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return true;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!');
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')');
}
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc.
* @private
*/
Collection.prototype.deferEmit = function () {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
if (this._changeTimeout) {
clearTimeout(this._changeTimeout);
}
// Set a timeout
this._changeTimeout = setTimeout(function () {
if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); }
self.emit.apply(self, args);
}, 100);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
*/
Collection.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this[type](dataArr);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
}
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
this._onInsert(inserted, failed);
if (callback) { callback(); }
this.deferEmit('change', {type: 'insert', data: inserted});
return {
inserted: inserted,
failed: failed
};
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {Object} item The item whose primary key should be used to lookup.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (item) {
return this._data.indexOf(
this._primaryIndex.get(
item[this._primaryKey]
)
);
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets the collection that this collection is a subset of.
* @returns {Collection}
*/
Collection.prototype.subsetOf = function () {
return this.__subsetOf;
};
/**
* Sets the collection that this collection is a subset of.
* @param {Collection} collection The collection to set as the parent of this subset.
* @returns {*} This object for chaining.
* @private
*/
Collection.prototype._subsetOf = function (collection) {
this.__subsetOf = collection;
return this;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
//finalQuery,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearch,
joinMulti,
joinRequire,
joinFindResults,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
matcher = function (doc) {
return self._match(doc, query, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(query, options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup;
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
op.time('tableScan: ' + scanLength);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
joinCollectionInstance = this._db.collection(joinCollectionName);
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearch = {};
joinMulti = false;
joinRequire = false;
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
/*default:
// Check for a double-dollar which is a back-reference to the root collection item
if (joinMatchIndex.substr(0, 3) === '$$.') {
// Back reference
// TODO: Support complex joins
}
break;*/
}
} else {
// TODO: Could optimise this by caching path objects
// Get the data to match against and store in the search object
joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0];
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearch);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query) {
var item = this.find(query, {$decouple: false})[0];
if (item) {
return this._data.indexOf(item);
}
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = sortKey;
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
buckets = this.bucket(keyObj.___fdbKey, arr);
// Loop buckets and sort contents
for (i in buckets) {
if (buckets.hasOwnProperty(i)) {
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i]));
}
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
buckets = {};
for (i = 0; i < arr.length; i++) {
buckets[arr[i][key]] = buckets[arr[i][key]] || [];
buckets[arr[i][key]].push(arr[i]);
}
return buckets;
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param match
* @param path
* @param subDocQuery
* @param subDocOptions
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
resultObj.subDocs.push(subDocResults);
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.noStats) {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
break;
case 'update':
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
break;
case 'remove':
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
break;
default:
}
});
},
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Core.prototype.collection = new Overload({
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {Object} options An options object.
* @returns {Collection}
*/
'object': function (options) {
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This get's called by all the other variants and
* handles the actual logic of the overloaded method.
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log('Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name).db(this);
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Core.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Core.prototype.collections = function (search) {
var arr = [],
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: this._collection[i].count()
});
}
} else {
arr.push({
name: i,
count: this._collection[i].count()
});
}
}
}
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":4,"./IndexBinaryTree":5,"./IndexHashMap":6,"./KeyValueStore":7,"./Metrics":8,"./Overload":19,"./Path":20,"./ReactorIO":21,"./Shared":22}],3:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The main ForerunnerDB core object.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.ChainReactor');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Core.prototype._isServer = false;
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Core.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Core.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Core.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Core.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Core.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Core.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Core.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
/**
* Drops all collections in the database.
* @param {Function=} callback Optional callback method.
*/
Core.prototype.drop = function (callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
}
return true;
};
module.exports = Core;
},{"./Collection.js":2,"./Crc.js":4,"./Metrics.js":8,"./Overload":19,"./Shared":22}],4:[function(_dereq_,module,exports){
"use strict";
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],5:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
btree = function () {};
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./Path":20,"./Shared":22}],6:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":20,"./Shared":22}],7:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":22}],8:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":18,"./Shared":22}],9:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],10:[function(_dereq_,module,exports){
"use strict";
// TODO: Document the methods in this mixin
var ChainReactor = {
chain: function (obj) {
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arr[index].chainReceive(this, type, data, options);
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],11:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return JSON.parse(JSON.stringify(data));
} else {
var i,
json = JSON.stringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(JSON.parse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
])
};
module.exports = Common;
},{"./Overload":19}],12:[function(_dereq_,module,exports){
"use strict";
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],13:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount;
// Handle global emit
if (this._listeners[event]['*']) {
var arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
var listenerIdArr = this._listeners[event],
listenerIdCount,
listenerIdIndex;
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{"./Overload":19}],14:[function(_dereq_,module,exports){
"use strict";
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
}
return -1;
}
};
module.exports = Matching;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],16:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":19}],17:[function(_dereq_,module,exports){
"use strict";
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item from the array stack.
* @param {Object} doc The document to modify.
* @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false;
if (doc.length > 0) {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":20,"./Shared":22}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":22}],21:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
ReactorIO.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":22}],22:[function(_dereq_,module,exports){
"use strict";
var Shared = {
version: '1.3.34',
modules: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
this.modules[name] = module;
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
this.modules[name]._fdbFinished = true;
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: function (obj, mixinName) {
var system = this.mixins[mixinName];
if (system) {
for (var i in system) {
if (system.hasOwnProperty(i)) {
obj[i] = system[i];
}
}
} else {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
},
/**
* Generates a generic getter/setter method for the passed method name.
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @param arr
* @returns {Function}
* @constructor
*/
overload: _dereq_('./Overload'),
/**
* Define the mixins that other modules can use as required.
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":9,"./Mixin.ChainReactor":10,"./Mixin.Common":11,"./Mixin.Constants":12,"./Mixin.Events":13,"./Mixin.Matching":14,"./Mixin.Sorting":15,"./Mixin.Triggers":16,"./Mixin.Updating":17,"./Overload":19}],23:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
src/ui/@state/@region/list/CountyList.component.js | andest01/trout-maps | import React from 'react'
import classes from './List.scss'
import { isEmpty } from 'lodash'
// import BubbleComponent from './Bubble.component'
// import StreamItemContainer from './streamItem/StreamItem.container'
import StreamListComponent from './StreamList.component'
const CountyListComponent = React.createClass({
propTypes: {
isListVisible: React.PropTypes.bool.isRequired,
visibleCounties: React.PropTypes.array.isRequired,
selectedState: React.PropTypes.string.isRequired,
selectedRegion: React.PropTypes.string.isRequired
},
componentDidMount () {
// console.log('LIST VIEW MOUNTED')
},
renderCounty (county, index) {
let { gid, name, streams } = county
return (<li key={gid}>
<div className={classes.listHeaderContainer}>
<div className={classes.listTitle}>{name} Co.</div>
</div>
<StreamListComponent
isListVisible={this.props.isListVisible}
visibleTroutStreams={streams}
selectedState={this.props.selectedState}
selectedRegion={this.props.selectedRegion} />
</li>)
},
renderCounties () {
let { visibleCounties } = this.props
if (isEmpty(visibleCounties)) {
return null
}
return (<ul >
{visibleCounties.map((county, index) => this.renderCounty(county, index))}
</ul>)
},
render () {
let { isListVisible } = this.props
return (
<div className={isListVisible ? classes.listViewContainer : classes.invisible}>
{this.renderCounties()}
<div className={classes.godAwfulPlaceholder} />
</div>)
}
})
export default CountyListComponent
|
src/files/info-boxes/InfoBoxes.js | ipfs/webui | import React from 'react'
import PropTypes from 'prop-types'
import CompanionInfo from './companion-info/CompanionInfo'
import AddFilesInfo from './add-files-info/AddFilesInfo'
const InfoBoxes = ({ isRoot, isCompanion, filesExist }) => (
<div>
{ isRoot && isCompanion && <CompanionInfo /> }
{ isRoot && !filesExist && !isCompanion && <AddFilesInfo /> }
</div>
)
InfoBoxes.propTypes = {
isRoot: PropTypes.bool.isRequired,
isCompanion: PropTypes.bool.isRequired,
filesExist: PropTypes.bool.isRequired
}
export default InfoBoxes
|
src/components/BookFilter.js | scottag99/dreamlibrary | import React from 'react';
import { observer } from 'mobx-react';
import { Checkbox, FormControl, ControlLabel, Row, Col, Radio, FormGroup } from 'react-bootstrap';
export default observer(({store}) => (
<Row>
<h3>Find Books</h3>
<Col sm={4} lg={3}>
<ControlLabel>Filter by Grade Level</ControlLabel>
<FormControl componentClass="select" placeholder="Select" onChange={store.handleGradeLevel} value={store.lvlFilter}>
<option value="">Select</option>
<option value="PreK-K">PreK-K</option>
<option value="G1-G2">G1-G2</option>
<option value="G3-G5">G3-G5</option>
</FormControl>
<Checkbox checked={store.chapters} onChange={store.handleChapterFilter}>
Chapter Only
</Checkbox>
</Col>
<Col sm={4} lg={3}>
<ControlLabel>Filter by GRL</ControlLabel>
<FormControl componentClass="select" placeholder="Select" onChange={store.handleGrlFilter} value={store.grlFilter}>
<option value="">Select</option>
<option value="A,B,C">A-C</option>
<option value="D,E,F,G,H,I">D-I</option>
<option value="J,K,L,M">J-M</option>
<option value="N,O,P">N-P</option>
<option value="Q,R,S,T">Q-T</option>
<option value="U,W,X,Y,Z">U-Z</option>
</FormControl>
<FormGroup>
<Radio name="bilingual-filter" id="all" onClick={store.handleBilingualFilter}>All</Radio>
<Radio name="bilingual-filter" id="bilingual" onClick={store.handleBilingualFilter}>Bilingual</Radio>
<Radio name="bilingual-filter" id="english" onClick={store.handleBilingualFilter}>English Only</Radio>
</FormGroup>
</Col>
<Col sm={4} lg={3}>
<ControlLabel inline>Filter by DRA</ControlLabel>
<FormControl componentClass="select" placeholder="Select" onChange={store.handleDraFilter} value={store.draFilter}>
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3-4">3-4</option>
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
<option value="24">24</option>
<option value="28">28</option>
<option value="30">30</option>
<option value="34">34</option>
<option value="38">38</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
</FormControl>
</Col>
</Row>
));
|
src/svg-icons/action/http.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHttp = (props) => (
<SvgIcon {...props}>
<path d="M4.5 11h-2V9H1v6h1.5v-2.5h2V15H6V9H4.5v2zm2.5-.5h1.5V15H10v-4.5h1.5V9H7v1.5zm5.5 0H14V15h1.5v-4.5H17V9h-4.5v1.5zm9-1.5H18v6h1.5v-2h2c.8 0 1.5-.7 1.5-1.5v-1c0-.8-.7-1.5-1.5-1.5zm0 2.5h-2v-1h2v1z"/>
</SvgIcon>
);
ActionHttp = pure(ActionHttp);
ActionHttp.displayName = 'ActionHttp';
ActionHttp.muiName = 'SvgIcon';
export default ActionHttp;
|
ajax/libs/reactable/0.11.2/reactable.js | voronianski/cdnjs | window.React["default"] = window.React;
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.filter_props_from = mod.exports;
}
})(this, function (exports) {
"use strict";
exports.filterPropsFrom = filterPropsFrom;
var internalProps = {
columns: true,
sortable: true,
filterable: true,
sortBy: true,
defaultSort: true,
itemsPerPage: true,
childNode: true,
data: true,
children: true
};
function filterPropsFrom(baseProps) {
baseProps = baseProps || {};
var props = {};
for (var key in baseProps) {
if (!(key in internalProps)) {
props[key] = baseProps[key];
}
}
return props;
}
});
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.to_array = mod.exports;
}
})(this, function (exports) {
"use strict";
exports.toArray = toArray;
function toArray(obj) {
var ret = [];
for (var attr in obj) {
ret[attr] = obj;
}
return ret;
}
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.stringable = mod.exports;
}
})(this, function (exports) {
'use strict';
exports.stringable = stringable;
function stringable(thing) {
return thing !== null && typeof thing !== 'undefined' && typeof (thing.toString === 'function');
}
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', './stringable'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('./stringable'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.stringable);
global.extract_data_from = mod.exports;
}
})(this, function (exports, _stringable) {
'use strict';
exports.extractDataFrom = extractDataFrom;
function extractDataFrom(key, column) {
var value;
if (typeof key !== 'undefined' && key !== null && key.__reactableMeta === true) {
value = key.data[column];
} else {
value = key[column];
}
if (typeof value !== 'undefined' && value !== null && value.__reactableMeta === true) {
value = typeof value.props.value !== 'undefined' && value.props.value !== null ? value.props.value : value.value;
}
return (0, _stringable.stringable)(value) ? value : '';
}
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.is_react_component = mod.exports;
}
})(this, function (exports) {
// this is a bit hacky - it'd be nice if React exposed an API for this
'use strict';
exports.isReactComponent = isReactComponent;
function isReactComponent(thing) {
return thing !== null && typeof thing === 'object' && typeof thing.props !== 'undefined';
}
});
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.unsafe = mod.exports;
}
})(this, function (exports) {
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports.unsafe = unsafe;
exports.isUnsafe = isUnsafe;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Unsafe = (function () {
function Unsafe(content) {
_classCallCheck(this, Unsafe);
this.content = content;
}
_createClass(Unsafe, [{
key: "toString",
value: function toString() {
return this.content;
}
}]);
return Unsafe;
})();
function unsafe(str) {
return new Unsafe(str);
}
;
function isUnsafe(obj) {
return obj instanceof Unsafe;
}
;
});
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "react"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("react"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React);
global.filterer = mod.exports;
}
})(this, function (exports, _react) {
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 FiltererInput = (function (_React$Component) {
_inherits(FiltererInput, _React$Component);
function FiltererInput() {
_classCallCheck(this, FiltererInput);
_get(Object.getPrototypeOf(FiltererInput.prototype), "constructor", this).apply(this, arguments);
}
_createClass(FiltererInput, [{
key: "onChange",
value: function onChange() {
this.props.onFilter(_react["default"].findDOMNode(this).value);
}
}, {
key: "render",
value: function render() {
return _react["default"].createElement("input", { type: "text",
className: "reactable-filter-input",
placeholder: this.props.placeholder,
value: this.props.value,
onKeyUp: this.onChange.bind(this),
onChange: this.onChange.bind(this) });
}
}]);
return FiltererInput;
})(_react["default"].Component);
exports.FiltererInput = FiltererInput;
;
var Filterer = (function (_React$Component2) {
_inherits(Filterer, _React$Component2);
function Filterer() {
_classCallCheck(this, Filterer);
_get(Object.getPrototypeOf(Filterer.prototype), "constructor", this).apply(this, arguments);
}
_createClass(Filterer, [{
key: "render",
value: function render() {
if (typeof this.props.colSpan === 'undefined') {
throw new TypeError('Must pass a colSpan argument to Filterer');
}
return _react["default"].createElement(
"tr",
{ className: "reactable-filterer" },
_react["default"].createElement(
"td",
{ colSpan: this.props.colSpan },
_react["default"].createElement(FiltererInput, { onFilter: this.props.onFilter,
value: this.props.value,
placeholder: this.props.placeholder })
)
);
}
}]);
return Filterer;
})(_react["default"].Component);
exports.Filterer = Filterer;
;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.sort = mod.exports;
}
})(this, function (exports) {
'use strict';
var Sort = {
Numeric: function Numeric(a, b) {
var valA = parseFloat(a.toString().replace(/,/g, ''));
var valB = parseFloat(b.toString().replace(/,/g, ''));
// Sort non-numeric values alphabetically at the bottom of the list
if (isNaN(valA) && isNaN(valB)) {
valA = a;
valB = b;
} else {
if (isNaN(valA)) {
return 1;
}
if (isNaN(valB)) {
return -1;
}
}
if (valA < valB) {
return -1;
}
if (valA > valB) {
return 1;
}
return 0;
},
NumericInteger: function NumericInteger(a, b) {
if (isNaN(a) || isNaN(b)) {
return a > b ? 1 : -1;
}
return a - b;
},
Currency: function Currency(a, b) {
// Parse out dollar signs, then do a regular numeric sort
// TODO: handle non-American currency
if (a[0] === '$') {
a = a.substring(1);
}
if (b[0] === '$') {
b = b.substring(1);
}
return exports.Sort.Numeric(a, b);
},
Date: (function (_Date) {
function Date(_x, _x2) {
return _Date.apply(this, arguments);
}
Date.toString = function () {
return _Date.toString();
};
return Date;
})(function (a, b) {
// Note: this function tries to do a standard javascript string -> date conversion
// If you need more control over the date string format, consider using a different
// date library and writing your own function
var valA = Date.parse(a);
var valB = Date.parse(b);
// Handle non-date values with numeric sort
// Sort non-numeric values alphabetically at the bottom of the list
if (isNaN(valA) || isNaN(valB)) {
return exports.Sort.Numeric(a, b);
}
if (valA > valB) {
return 1;
}
if (valB > valA) {
return -1;
}
return 0;
}),
CaseInsensitive: function CaseInsensitive(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
}
};
exports.Sort = Sort;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './lib/is_react_component', './lib/stringable', './unsafe'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./lib/is_react_component'), require('./lib/stringable'), require('./unsafe'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.is_react_component, global.stringable, global.unsafe);
global.td = mod.exports;
}
})(this, function (exports, _react, _libIs_react_component, _libStringable, _unsafe) {
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Td = (function (_React$Component) {
_inherits(Td, _React$Component);
function Td() {
_classCallCheck(this, Td);
_get(Object.getPrototypeOf(Td.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Td, [{
key: 'handleClick',
value: function handleClick(e) {
if (typeof this.props.handleClick === 'function') {
return this.props.handleClick(e, this);
}
}
}, {
key: 'render',
value: function render() {
var tdProps = {
className: this.props.className,
onClick: this.handleClick.bind(this)
};
// Attach any properties on the column to this Td object to allow things like custom event handlers
if (typeof this.props.column === 'object') {
for (var key in this.props.column) {
if (key !== 'key' && key !== 'name') {
tdProps[key] = this.props.column[key];
}
}
}
var data = this.props.data;
if (typeof this.props.children !== 'undefined') {
if ((0, _libIs_react_component.isReactComponent)(this.props.children)) {
data = this.props.children;
} else if (typeof this.props.data === 'undefined' && (0, _libStringable.stringable)(this.props.children)) {
data = this.props.children.toString();
}
if ((0, _unsafe.isUnsafe)(this.props.children)) {
tdProps.dangerouslySetInnerHTML = { __html: this.props.children.toString() };
} else {
tdProps.children = data;
}
}
return _react['default'].createElement('td', tdProps);
}
}]);
return Td;
})(_react['default'].Component);
exports.Td = Td;
;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './td', './lib/to_array', './lib/filter_props_from'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./td'), require('./lib/to_array'), require('./lib/filter_props_from'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.td, global.to_array, global.filter_props_from);
global.tr = mod.exports;
}
})(this, function (exports, _react, _td, _libTo_array, _libFilter_props_from) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Tr = (function (_React$Component) {
_inherits(Tr, _React$Component);
function Tr() {
_classCallCheck(this, Tr);
_get(Object.getPrototypeOf(Tr.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Tr, [{
key: 'render',
value: function render() {
var children = (0, _libTo_array.toArray)(_react['default'].Children.children(this.props.children));
if (this.props.data && this.props.columns && typeof this.props.columns.map === 'function') {
if (typeof children.concat === 'undefined') {
console.log(children);
}
children = children.concat(this.props.columns.map((function (column, i) {
if (this.props.data.hasOwnProperty(column.key)) {
var value = this.props.data[column.key];
var props = {};
if (typeof value !== 'undefined' && value !== null && value.__reactableMeta === true) {
props = value.props;
value = value.value;
}
return _react['default'].createElement(
_td.Td,
_extends({ column: column, key: column.key }, props),
value
);
} else {
return _react['default'].createElement(_td.Td, { column: column, key: column.key });
}
}).bind(this)));
}
// Manually transfer props
var props = (0, _libFilter_props_from.filterPropsFrom)(this.props);
return _react['default'].DOM.tr(props, children);
}
}]);
return Tr;
})(_react['default'].Component);
exports.Tr = Tr;
;
Tr.childNode = _td.Td;
Tr.dataType = 'object';
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './unsafe', './lib/filter_props_from'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./unsafe'), require('./lib/filter_props_from'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.unsafe, global.filter_props_from);
global.th = mod.exports;
}
})(this, function (exports, _react, _unsafe, _libFilter_props_from) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Th = (function (_React$Component) {
_inherits(Th, _React$Component);
function Th() {
_classCallCheck(this, Th);
_get(Object.getPrototypeOf(Th.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Th, [{
key: 'render',
value: function render() {
var childProps = undefined;
if ((0, _unsafe.isUnsafe)(this.props.children)) {
return _react['default'].createElement('th', _extends({}, (0, _libFilter_props_from.filterPropsFrom)(this.props), {
dangerouslySetInnerHTML: { __html: this.props.children.toString() } }));
} else {
return _react['default'].createElement(
'th',
(0, _libFilter_props_from.filterPropsFrom)(this.props),
this.props.children
);
}
}
}]);
return Th;
})(_react['default'].Component);
exports.Th = Th;
;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './th', './filterer', './lib/filter_props_from'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./th'), require('./filterer'), require('./lib/filter_props_from'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.th, global.filterer, global.filter_props_from);
global.thead = mod.exports;
}
})(this, function (exports, _react, _th, _filterer, _libFilter_props_from) {
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Thead = (function (_React$Component) {
_inherits(Thead, _React$Component);
function Thead() {
_classCallCheck(this, Thead);
_get(Object.getPrototypeOf(Thead.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Thead, [{
key: 'handleClickTh',
value: function handleClickTh(column) {
this.props.onSort(column.key);
}
}, {
key: 'render',
value: function render() {
// Declare the list of Ths
var Ths = [];
for (var index = 0; index < this.props.columns.length; index++) {
var column = this.props.columns[index];
var thClass = 'reactable-th-' + column.key.replace(/\s+/g, '-').toLowerCase();
var sortClass = '';
if (this.props.sortableColumns[column.key]) {
sortClass += 'reactable-header-sortable ';
}
if (this.props.sort.column === column.key) {
sortClass += 'reactable-header-sort';
if (this.props.sort.direction === 1) {
sortClass += '-asc';
} else {
sortClass += '-desc';
}
}
if (sortClass.length > 0) {
thClass += ' ' + sortClass;
}
Ths.push(_react['default'].createElement(
_th.Th,
{ className: thClass, key: index, onClick: this.handleClickTh.bind(this, column) },
column.label
));
}
// Manually transfer props
var props = (0, _libFilter_props_from.filterPropsFrom)(this.props);
return _react['default'].createElement(
'thead',
props,
this.props.filtering === true ? _react['default'].createElement(_filterer.Filterer, {
colSpan: this.props.columns.length,
onFilter: this.props.onFilter,
placeholder: this.props.filterPlaceholder,
value: this.props.currentFilter
}) : null,
_react['default'].createElement(
'tr',
{ className: 'reactable-column-header' },
Ths
)
);
}
}], [{
key: 'getColumns',
value: function getColumns(component) {
// Can't use React.Children.map since that doesn't return a proper array
var columns = [];
_react['default'].Children.forEach(component.props.children, function (th) {
if (typeof th.props.children === 'string') {
columns.push(th.props.children);
} else if (typeof th.props.column === 'string') {
columns.push({
key: th.props.column,
label: th.props.children
});
} else {
throw new TypeError('<th> must have either a "column" property or a string ' + 'child');
}
});
return columns;
}
}]);
return Thead;
})(_react['default'].Component);
exports.Thead = Thead;
;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React);
global.tfoot = mod.exports;
}
})(this, function (exports, _react) {
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Tfoot = (function (_React$Component) {
_inherits(Tfoot, _React$Component);
function Tfoot() {
_classCallCheck(this, Tfoot);
_get(Object.getPrototypeOf(Tfoot.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Tfoot, [{
key: 'render',
value: function render() {
return _react['default'].createElement('tfoot', this.props);
}
}]);
return Tfoot;
})(_react['default'].Component);
exports.Tfoot = Tfoot;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React);
global.paginator = mod.exports;
}
})(this, function (exports, _react) {
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Paginator = (function (_React$Component) {
_inherits(Paginator, _React$Component);
function Paginator() {
_classCallCheck(this, Paginator);
_get(Object.getPrototypeOf(Paginator.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Paginator, [{
key: 'handlePrevious',
value: function handlePrevious() {
this.props.onPageChange(this.props.currentPage - 1);
}
}, {
key: 'handleNext',
value: function handleNext() {
this.props.onPageChange(this.props.currentPage + 1);
}
}, {
key: 'handlePageButton',
value: function handlePageButton(page) {
this.props.onPageChange(page);
}
}, {
key: 'renderPrevious',
value: function renderPrevious() {
if (this.props.currentPage > 0) {
return _react['default'].createElement(
'a',
{ className: 'reactable-previous-page', onClick: this.handlePrevious.bind(this) },
'Previous'
);
}
}
}, {
key: 'renderNext',
value: function renderNext() {
if (this.props.currentPage < this.props.numPages - 1) {
return _react['default'].createElement(
'a',
{ className: 'reactable-next-page', onClick: this.handleNext.bind(this) },
'Next'
);
}
}
}, {
key: 'renderPageButton',
value: function renderPageButton(className, pageNum) {
return _react['default'].createElement(
'a',
{ className: className, key: pageNum, onClick: this.handlePageButton.bind(this, pageNum) },
pageNum + 1
);
}
}, {
key: 'render',
value: function render() {
if (typeof this.props.colSpan === 'undefined') {
throw new TypeError('Must pass a colSpan argument to Paginator');
}
if (typeof this.props.numPages === 'undefined') {
throw new TypeError('Must pass a non-zero numPages argument to Paginator');
}
if (typeof this.props.currentPage === 'undefined') {
throw new TypeError('Must pass a currentPage argument to Paginator');
}
var pageButtons = [];
var pageButtonLimit = this.props.pageButtonLimit;
var currentPage = this.props.currentPage;
var numPages = this.props.numPages;
var lowerHalf = Math.round(pageButtonLimit / 2);
var upperHalf = pageButtonLimit - lowerHalf;
for (var i = 0; i < this.props.numPages; i++) {
var showPageButton = false;
var pageNum = i;
var className = "reactable-page-button";
if (currentPage === i) {
className += " reactable-current-page";
}
pageButtons.push(this.renderPageButton(className, pageNum));
}
if (currentPage - pageButtonLimit + lowerHalf > 0) {
if (currentPage > numPages - lowerHalf) {
pageButtons.splice(0, numPages - pageButtonLimit);
} else {
pageButtons.splice(0, currentPage - pageButtonLimit + lowerHalf);
}
}
if (numPages - currentPage > upperHalf) {
pageButtons.splice(pageButtonLimit, pageButtons.length - pageButtonLimit);
}
return _react['default'].createElement(
'tbody',
{ className: 'reactable-pagination' },
_react['default'].createElement(
'tr',
null,
_react['default'].createElement(
'td',
{ colSpan: this.props.colSpan },
this.renderPrevious(),
pageButtons,
this.renderNext()
)
)
);
}
}]);
return Paginator;
})(_react['default'].Component);
exports.Paginator = Paginator;
;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './lib/filter_props_from', './lib/extract_data_from', './unsafe', './thead', './th', './tr', './tfoot', './paginator'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./lib/filter_props_from'), require('./lib/extract_data_from'), require('./unsafe'), require('./thead'), require('./th'), require('./tr'), require('./tfoot'), require('./paginator'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.filter_props_from, global.extract_data_from, global.unsafe, global.thead, global.th, global.tr, global.tfoot, global.paginator);
global.table = mod.exports;
}
})(this, function (exports, _react, _libFilter_props_from, _libExtract_data_from, _unsafe, _thead, _th, _tr, _tfoot, _paginator) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _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 Table = (function (_React$Component) {
_inherits(Table, _React$Component);
function Table(props) {
_classCallCheck(this, Table);
_get(Object.getPrototypeOf(Table.prototype), 'constructor', this).call(this, props);
this.state = {
currentPage: 0,
currentSort: {
column: null,
direction: 1
},
filter: ''
};
// Set the state of the current sort to the default sort
if (props.sortBy !== false || props.defaultSort !== false) {
var sortingColumn = props.sortBy || props.defaultSort;
this.state.currentSort = this.getCurrentSort(sortingColumn);
}
}
_createClass(Table, [{
key: 'filterBy',
value: function filterBy(filter) {
this.setState({ filter: filter });
}
// Translate a user defined column array to hold column objects if strings are specified
// (e.g. ['column1'] => [{key: 'column1', label: 'column1'}])
}, {
key: 'translateColumnsArray',
value: function translateColumnsArray(columns) {
return columns.map((function (column, i) {
if (typeof column === 'string') {
return {
key: column,
label: column
};
} else {
if (typeof column.sortable !== 'undefined') {
var sortFunction = column.sortable === true ? 'default' : column.sortable;
this._sortable[column.key] = sortFunction;
}
return column;
}
}).bind(this));
}
}, {
key: 'parseChildData',
value: function parseChildData(props) {
var data = [],
tfoot = undefined;
// Transform any children back to a data array
if (typeof props.children !== 'undefined') {
_react['default'].Children.forEach(props.children, (function (child) {
if (typeof child === 'undefined' || child === null) {
return;
}
switch (child.type) {
case _tfoot.Tfoot:
if (typeof tfoot !== 'undefined') {
console.warn('You can only have one <Tfoot>, but more than one was specified.' + 'Ignoring all but the last one');
}
tfoot = child;
break;
case _tr.Tr:
var childData = child.props.data || {};
_react['default'].Children.forEach(child.props.children, function (descendant) {
// TODO
/* if (descendant.type.ConvenienceConstructor === Td) { */
if (typeof descendant !== 'object' || descendant == null) {
return;
} else if (typeof descendant.props.column !== 'undefined') {
var value = undefined;
if (typeof descendant.props.data !== 'undefined') {
value = descendant.props.data;
} else if (typeof descendant.props.children !== 'undefined') {
value = descendant.props.children;
} else {
console.warn('exports.Td specified without ' + 'a `data` property or children, ' + 'ignoring');
return;
}
childData[descendant.props.column] = {
value: value,
props: (0, _libFilter_props_from.filterPropsFrom)(descendant.props),
__reactableMeta: true
};
} else {
console.warn('exports.Td specified without a ' + '`column` property, ignoring');
}
});
data.push({
data: childData,
props: (0, _libFilter_props_from.filterPropsFrom)(child.props),
__reactableMeta: true
});
break;
}
}).bind(this));
}
return { data: data, tfoot: tfoot };
}
}, {
key: 'initialize',
value: function initialize(props) {
this.data = props.data || [];
var _parseChildData = this.parseChildData(props);
var data = _parseChildData.data;
var tfoot = _parseChildData.tfoot;
this.data = this.data.concat(data);
this.tfoot = tfoot;
this.initializeSorts(props);
}
}, {
key: 'initializeSorts',
value: function initializeSorts() {
this._sortable = {};
// Transform sortable properties into a more friendly list
for (var i in this.props.sortable) {
var column = this.props.sortable[i];
var columnName = undefined,
sortFunction = undefined;
if (column instanceof Object) {
if (typeof column.column !== 'undefined') {
columnName = column.column;
} else {
console.warn('Sortable column specified without column name');
return;
}
if (typeof column.sortFunction === 'function') {
sortFunction = column.sortFunction;
} else {
sortFunction = 'default';
}
} else {
columnName = column;
sortFunction = 'default';
}
this._sortable[columnName] = sortFunction;
}
}
}, {
key: 'getCurrentSort',
value: function getCurrentSort(column) {
var columnName = undefined,
sortDirection = undefined;
if (column instanceof Object) {
if (typeof column.column !== 'undefined') {
columnName = column.column;
} else {
console.warn('Default column specified without column name');
return;
}
if (typeof column.direction !== 'undefined') {
if (column.direction === 1 || column.direction === 'asc') {
sortDirection = 1;
} else if (column.direction === -1 || column.direction === 'desc') {
sortDirection = -1;
} else {
console.warn('Invalid default sort specified. Defaulting to ascending');
sortDirection = 1;
}
} else {
sortDirection = 1;
}
} else {
columnName = column;
sortDirection = 1;
}
return {
column: columnName,
direction: sortDirection
};
}
}, {
key: 'updateCurrentSort',
value: function updateCurrentSort(sortBy) {
if (sortBy !== false && sortBy.column !== this.state.currentSort.column && sortBy.direction !== this.state.currentSort.direction) {
this.setState({ currentSort: this.getCurrentSort(sortBy) });
}
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
this.initialize(this.props);
this.sortByCurrentSort();
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.initialize(nextProps);
this.updateCurrentSort(nextProps.sortBy);
this.sortByCurrentSort();
}
}, {
key: 'applyFilter',
value: function applyFilter(filter, children) {
// Helper function to apply filter text to a list of table rows
filter = filter.toLowerCase();
var matchedChildren = [];
for (var i = 0; i < children.length; i++) {
var data = children[i].props.data;
for (var j = 0; j < this.props.filterable.length; j++) {
var filterColumn = this.props.filterable[j];
if (typeof data[filterColumn] !== 'undefined' && (0, _libExtract_data_from.extractDataFrom)(data, filterColumn).toString().toLowerCase().indexOf(filter) > -1) {
matchedChildren.push(children[i]);
break;
}
}
}
return matchedChildren;
}
}, {
key: 'sortByCurrentSort',
value: function sortByCurrentSort() {
// Apply a sort function according to the current sort in the state.
// This allows us to perform a default sort even on a non sortable column.
var currentSort = this.state.currentSort;
if (currentSort.column === null) {
return;
}
this.data.sort((function (a, b) {
var keyA = (0, _libExtract_data_from.extractDataFrom)(a, currentSort.column);
keyA = (0, _unsafe.isUnsafe)(keyA) ? keyA.toString() : keyA || '';
var keyB = (0, _libExtract_data_from.extractDataFrom)(b, currentSort.column);
keyB = (0, _unsafe.isUnsafe)(keyB) ? keyB.toString() : keyB || '';
// Default sort
if (typeof this._sortable[currentSort.column] === 'undefined' || this._sortable[currentSort.column] === 'default') {
// Reverse direction if we're doing a reverse sort
if (keyA < keyB) {
return -1 * currentSort.direction;
}
if (keyA > keyB) {
return 1 * currentSort.direction;
}
return 0;
} else {
// Reverse columns if we're doing a reverse sort
if (currentSort.direction === 1) {
return this._sortable[currentSort.column](keyA, keyB);
} else {
return this._sortable[currentSort.column](keyB, keyA);
}
}
}).bind(this));
}
}, {
key: 'onSort',
value: function onSort(column) {
// Don't perform sort on unsortable columns
if (typeof this._sortable[column] === 'undefined') {
return;
}
var currentSort = this.state.currentSort;
if (currentSort.column === column) {
currentSort.direction *= -1;
} else {
currentSort.column = column;
currentSort.direction = 1;
}
// Set the current sort and pass it to the sort function
this.setState({ currentSort: currentSort });
this.sortByCurrentSort();
}
}, {
key: 'render',
value: function render() {
var _this = this;
var children = [];
var columns = undefined;
var userColumnsSpecified = false;
var firstChild = null;
if (this.props.children && this.props.children.length > 0 && this.props.children[0].type === _thead.Thead) {
fistChild = this.props.children[0];
} else if (typeof this.props.children !== 'undefined' && this.props.children.type === _thead.Thead) {
firstChild = this.props.children;
}
if (firstChild !== null) {
columns = _thead.Thead.getColumns(firstChild);
} else {
columns = this.props.columns || [];
}
if (columns.length > 0) {
userColumnsSpecified = true;
columns = this.translateColumnsArray(columns);
}
// Build up table rows
if (this.data && typeof this.data.map === 'function') {
// Build up the columns array
children = children.concat(this.data.map((function (rawData, i) {
var data = rawData;
var props = {};
if (rawData.__reactableMeta === true) {
data = rawData.data;
props = rawData.props;
}
// Loop through the keys in each data row and build a td for it
for (var k in data) {
if (data.hasOwnProperty(k)) {
// Update the columns array with the data's keys if columns were not
// already specified
if (userColumnsSpecified === false) {
(function () {
var column = {
key: k,
label: k
};
// Only add a new column if it doesn't already exist in the columns array
if (columns.find(function (element) {
return element.key === column.key;
}) === undefined) {
columns.push(column);
}
})();
}
}
}
return _react['default'].createElement(_tr.Tr, _extends({ columns: columns, key: i, data: data }, props));
}).bind(this)));
}
if (this.props.sortable === true) {
for (var i = 0; i < columns.length; i++) {
this._sortable[columns[i].key] = 'default';
}
}
// Determine if we render the filter box
var filtering = false;
if (this.props.filterable && Array.isArray(this.props.filterable) && this.props.filterable.length > 0) {
filtering = true;
}
// Apply filters
var filteredChildren = children;
if (this.state.filter !== '') {
filteredChildren = this.applyFilter(this.state.filter, filteredChildren);
}
// Determine pagination properties and which columns to display
var itemsPerPage = 0;
var pagination = false;
var numPages = undefined;
var currentPage = this.state.currentPage;
var pageButtonLimit = this.props.pageButtonLimit || 10;
var currentChildren = filteredChildren;
if (this.props.itemsPerPage > 0) {
itemsPerPage = this.props.itemsPerPage;
numPages = Math.ceil(filteredChildren.length / itemsPerPage);
if (currentPage > numPages - 1) {
currentPage = numPages - 1;
}
pagination = true;
currentChildren = filteredChildren.slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage);
}
// Manually transfer props
var props = (0, _libFilter_props_from.filterPropsFrom)(this.props);
return _react['default'].createElement(
'table',
props,
columns && columns.length > 0 ? _react['default'].createElement(_thead.Thead, { columns: columns,
filtering: filtering,
onFilter: function (filter) {
_this.setState({ filter: filter });
},
filterPlaceholder: this.props.filterPlaceholder,
currentFilter: this.state.filter,
sort: this.state.currentSort,
sortableColumns: this._sortable,
onSort: this.onSort.bind(this),
key: 'thead' }) : null,
_react['default'].createElement(
'tbody',
{ className: 'reactable-data', key: 'tbody' },
currentChildren
),
pagination === true ? _react['default'].createElement(_paginator.Paginator, { colSpan: columns.length,
pageButtonLimit: pageButtonLimit,
numPages: numPages,
currentPage: currentPage,
onPageChange: function (page) {
_this.setState({ currentPage: page });
},
key: 'paginator' }) : null,
this.tfoot
);
}
}]);
return Table;
})(_react['default'].Component);
exports.Table = Table;
Table.defaultProps = {
sortBy: false,
defaultSort: false,
itemsPerPage: 0
};
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'react', './reactable/table', './reactable/tr', './reactable/td', './reactable/tfoot', './reactable/thead', './reactable/sort', './reactable/unsafe'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('react'), require('./reactable/table'), require('./reactable/tr'), require('./reactable/td'), require('./reactable/tfoot'), require('./reactable/thead'), require('./reactable/sort'), require('./reactable/unsafe'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.React, global.table, global.tr, global.td, global.tfoot, global.thead, global.sort, global.unsafe);
global.reactable = mod.exports;
}
})(this, function (exports, _react, _reactableTable, _reactableTr, _reactableTd, _reactableTfoot, _reactableThead, _reactableSort, _reactableUnsafe) {
'use strict';
_react['default'].Children.children = function (children) {
return _react['default'].Children.map(children, function (x) {
return x;
}) || [];
};
// Array.prototype.find polyfill - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
configurable: true,
writable: true,
value: function value(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
if (i in list) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
}
return undefined;
}
});
}
var Reactable = { Table: _reactableTable.Table, Tr: _reactableTr.Tr, Td: _reactableTd.Td, Tfoot: _reactableTfoot.Tfoot, Thead: _reactableThead.Thead, Sort: _reactableSort.Sort, unsafe: _reactableUnsafe.unsafe };
exports['default'] = Reactable;
if (typeof window !== 'undefined') {
window.Reactable = Reactable;
}
});
|
manager/__tests__/index.android.js | dunkvalio/ReactNative | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
app/components/specificComponents/CommentaryCard/index.js | romainquellec/cuistot | import React from 'react';
import Rating from 'components/genericComponents/Rating';
import BlockComment from './blockcomment';
import Container from './container';
import SectionHeader from './sectionHeader';
import CommentaryForm from 'components/specificComponents/CommentaryForm';
import AddComment from 'components/specificComponents/CommentaryForm';
import Textarea from 'components/specificComponents/CommentaryForm/textareaStyled';
import Select from 'components/specificComponents/CommentaryForm/selectStyled';
import Submit from 'components/specificComponents/CommentaryForm/submitStyled';
export default class CommentaryCard extends React.Component {
createCommentary(commentary) {
return (
<BlockComment key={commentary.comment_id}>
<Rating rating={commentary.rating} />
<p>
{commentary.commentary}
</p>
</BlockComment>
);
}
createComments(comments) {
return comments.map(this.createCommentary);
}
submit(values) {
// print the form values to the console
console.log(values);
}
render() {
const commentary = this.props.commentary;
const nb = commentary.length;
let my = 0;
for (let i = 0; i < nb; i++) {
my += commentary[i].rating;
}
my /= nb;
return (
<Container>
<SectionHeader>
Commentaires <Rating rating={my} /> ({nb})
</SectionHeader>
{this.createComments(commentary)}
<AddComment id={this.props.id} />
</Container>
);
}
}
|
frontend/src/TermDates.js | googleinterns/step78-2020 | import React from 'react';
import TextField from '@material-ui/core/TextField';
import {CardContent} from '@material-ui/core';
class TermDates extends React.Component {
constructor(props) {
super(props);
this.handleStartDateChange = this.handleStartDateChange.bind(this);
this.handleEndDateChange = this.handleEndDateChange.bind(this);
}
handleStartDateChange(event) {
this.props.updateTermStartDate(event.target.value);
}
handleEndDateChange(event) {
this.props.updateTermEndDate(event.target.value);
}
render() {
return (
<CardContent>
<TextField label="Term start date:" type="date" onChange={this.handleStartDateChange}
value={this.props.startDate} InputLabelProps={{shrink: true}}
/>
<TextField label="Term end date:" type="date" onChange={this.handleEndDateChange}
value={this.props.endDate} InputLabelProps={{shrink: true}}
/>
</CardContent>
);
}
}
export default TermDates;
|
src/components/common/svg-icons/action/accessibility.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccessibility = (props) => (
<SvgIcon {...props}>
<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"/>
</SvgIcon>
);
ActionAccessibility = pure(ActionAccessibility);
ActionAccessibility.displayName = 'ActionAccessibility';
ActionAccessibility.muiName = 'SvgIcon';
export default ActionAccessibility;
|
src/components/Interactive/ToolTip/index.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import { makeId } from 'constants/HelperFunctions'
import styles from './style.module.css'
const ToolTip = (props) => {
const id = makeId(15)
return (
<div aria-labelledby={id} className={styles.tooltip}>{props.value}
<span role='tooltip' id={id} className={styles.tooltiptext}>{props.message}</span>
</div>
)
}
ToolTip.propTypes = {
value: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
}
export default ToolTip
|
src/AutoComplete/AutoComplete.spec.js | pomerantsev/material-ui | /* eslint-env mocha */
import React from 'react';
import {assert} from 'chai';
import AutoComplete from './AutoComplete';
import {shallow} from 'enzyme';
import getMuiTheme from '../styles/getMuiTheme';
describe('<AutoComplete />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
it('search using fuzzy filter', () => {
assert.strictEqual(AutoComplete.fuzzyFilter('ea', 'Peach'), true, 'should match Peach with ea');
assert.strictEqual(AutoComplete.fuzzyFilter('pah', 'Peach'), true, 'should match Peach with pah');
assert.strictEqual(AutoComplete.fuzzyFilter('peach', 'Peach'), true, 'should match Peach with peach');
assert.strictEqual(AutoComplete.fuzzyFilter('phc', 'Peach'), false, 'should not match Peach with phc');
assert.strictEqual(AutoComplete.fuzzyFilter('pp', 'Peach'), false, 'should not match Peach with pp');
assert.strictEqual(AutoComplete.fuzzyFilter('pb', 'Peach'), false, 'should not match Peach with pb');
// testing longer string
const test_string = 'The best thing about a Boolean is even if you are wrong, you are only off by a bit.';
let search_result = AutoComplete.fuzzyFilter('bOOLEAN', test_string);
assert.strictEqual(search_result, true, 'should match with case insensitive');
search_result = AutoComplete.fuzzyFilter('The a Boolean if wrong', test_string);
assert.strictEqual(search_result, true, 'should match pattern with spaces');
search_result = AutoComplete.fuzzyFilter(' if ,bit.', test_string);
assert.strictEqual(search_result, true, 'should match pattern with comma and period');
search_result = AutoComplete.fuzzyFilter('the best q', test_string);
assert.strictEqual(search_result, false, 'should not match pattern with letter is not contained in search text');
search_result = AutoComplete.fuzzyFilter('off bit by', 'off by a bit');
assert.strictEqual(search_result, false, 'should not match pattern when can not find letters in order ');
});
/**
* This test ensures that <AutoComplete /> doesn't pass down filter property to <TextField />,
* otherwise <TextField /> will render input as <input filter="function (...) {...}" ... />,
* which will have different behaviors in different environments, producing indent conflicts and
* breaking server rendering.
* Read more: https://github.com/callemall/material-ui/issues/4195
*/
it('should not pass filter property to children', () => {
const wrapper = shallowWithContext(
<AutoComplete dataSource={[]} />
);
assert.strictEqual(
wrapper.find('TextField').prop('filter'),
undefined,
'should not pass filter property to children');
});
});
|
ajax/libs/ember-data.js/1.0.0-beta.15/ember-data.js | dhenson02/cdnjs | (function() {
"use strict";
/**
@module ember-data
*/
var ember$data$lib$system$adapter$$get = Ember.get;
var ember$data$lib$system$adapter$$errorProps = [
'description',
'fileName',
'lineNumber',
'message',
'name',
'number',
'stack'
];
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
This function should return the entire payload as received from the
server. Error object extraction and normalization of model errors
should be performed by `extractErrors` on the serializer.
Example
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
The `DS.InvalidError` must be constructed with a single object whose
keys are the invalid model properties, and whose values contain
arrays of the corresponding error messages. For example:
```javascript
return new DS.InvalidError({
length: ['Must be less than 15'],
name: ['Must not be blank']
});
```
@class InvalidError
@namespace DS
*/
function ember$data$lib$system$adapter$$InvalidError(errors) {
var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
for (var i=0, l=ember$data$lib$system$adapter$$errorProps.length; i<l; i++) {
this[ember$data$lib$system$adapter$$errorProps[i]] = tmp[ember$data$lib$system$adapter$$errorProps[i]];
}
}
ember$data$lib$system$adapter$$InvalidError.prototype = Ember.create(Error.prototype);
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
Create a new subclass of `DS.Adapter`, then assign
it to the `ApplicationAdapter` property of the application.
```javascript
var MyAdapter = DS.Adapter.extend({
// ...your code here
});
App.ApplicationAdapter = MyAdapter;
```
Model-specific adapters can be created by assigning your adapter
class to the `ModelName` + `Adapter` property of the application.
```javascript
var MyPostAdapter = DS.Adapter.extend({
// ...Post-specific adapter code goes here
});
App.PostAdapter = MyPostAdapter;
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var ember$data$lib$system$adapter$$Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority than
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```javascript
var DjangoAdapter = DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
find: function(store, type, id) {
var url = [type.typeKey, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: Ember.required(Function),
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, inputProperties) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {String|Number} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Model} record
@param {Object} options
@return {Object} serialized record
*/
serialize: function(record, options) {
var snapshot = record._createSnapshot();
return ember$data$lib$system$adapter$$get(record, 'store').serializerFor(snapshot.typeKey).serialize(snapshot, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
updateRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
deleteRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: Ember.required(Function),
/**
By default the store will try to coalesce all `fetchRecord` calls within the same runloop
into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call.
You can opt out of this behaviour by either not implementing the findMany hook or by setting
coalesceFindRequests to false
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: true,
/**
Find multiple records at once if coalesceFindRequests is true
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the records
@param {Array} ids
@param {Array} records
@return {Promise} promise
*/
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
For example, if your api has nested URLs that depend on the parent, you will
want to group records by their parent.
The default implementation returns the records as a single group.
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} records
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, records) {
return [records];
}
});
var ember$data$lib$system$adapter$$default = ember$data$lib$system$adapter$$Adapter;
/**
@module ember-data
*/
var ember$data$lib$adapters$fixture_adapter$$get = Ember.get;
var ember$data$lib$adapters$fixture_adapter$$fmt = Ember.String.fmt;
var ember$data$lib$adapters$fixture_adapter$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$adapters$fixture_adapter$$counter = 0;
var ember$data$lib$adapters$fixture_adapter$$default = ember$data$lib$system$adapter$$default.extend({
// by default, fixtures are already in normalized form
serializer: null,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {Subclass of DS.Model} type
@return {Array}
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture) {
var fixtureIdType = typeof fixture.id;
if (fixtureIdType !== "number" && fixtureIdType !== "string") {
throw new Error(ember$data$lib$adapters$fixture_adapter$$fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixture
@param {Object} query
@param {Subclass of DS.Model} type
@return {Promise|Array}
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
/**
@method updateFixtures
@param {Subclass of DS.Model} type
@param {Array} fixture
*/
updateFixtures: function(type, fixture) {
if (!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {DS.Store} store
@param {Subclass of DS.Model} type
@param {DS.Model} record
*/
mockJSON: function(store, type, record) {
var snapshot = record._createSnapshot();
return store.serializerFor(snapshot.typeKey).serialize(snapshot, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String} id
*/
generateIdForRecord: function(store) {
return "fixture-" + ember$data$lib$adapters$fixture_adapter$$counter++;
},
/**
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: function(store, type, id) {
var fixtures = this.fixturesForType(type);
var fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString() +". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findBy('id', id);
}
if (fixture) {
return this.simulateRemoteCall(function() {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return ember$data$lib$adapters$fixture_adapter$$indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
this.deleteLoadedFixture(type, record);
return this.simulateRemoteCall(function() {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param type
@param record
*/
deleteLoadedFixture: function(type, record) {
var existingFixture = this.findExistingFixture(type, record);
if (existingFixture) {
var index = ember$data$lib$adapters$fixture_adapter$$indexOf(type.FIXTURES, existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param type
@param record
*/
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = ember$data$lib$adapters$fixture_adapter$$get(record, 'id');
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function(fixtures, id) {
return Ember.A(fixtures).find(function(r) {
if (''+ember$data$lib$adapters$fixture_adapter$$get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function(callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve) {
var value = Ember.copy(callback.call(context), true);
if (ember$data$lib$adapters$fixture_adapter$$get(adapter, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(function() {
resolve(value);
}, ember$data$lib$adapters$fixture_adapter$$get(adapter, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule('actions', null, function() {
resolve(value);
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
/*
The Map/MapWithDefault/OrderedSet code has been in flux as we try
to catch up with ES6. This is difficult as we support multiple
versions of Ember.
This file is currently here in case we have to polyfill ember's code
across a few releases. As ES6 comes to a close we should have a smaller
and smaller gap in implementations between Ember releases.
*/
var ember$data$lib$system$map$$Map = Ember.Map;
var ember$data$lib$system$map$$MapWithDefault = Ember.MapWithDefault;
var ember$data$lib$system$map$$OrderedSet = Ember.OrderedSet;
var ember$data$lib$system$map$$default = ember$data$lib$system$map$$Map;
var ember$data$lib$adapters$rest_adapter$$get = Ember.get;
var ember$data$lib$adapters$rest_adapter$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$adapters$rest_adapter$$default = ember$data$lib$system$adapter$$Adapter.extend({
defaultSerializer: '-rest',
/**
By default, the RESTAdapter will send the query params sorted alphabetically to the
server.
For example:
```js
store.find('posts', {sort: 'price', category: 'pets'});
```
will generate a requests like this `/posts?category=pets&sort=price`, even if the
parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms
in the backend.
Setting `sortQueryParams` to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set
`sortQueryParams` to your custom sort function.
```js
export default DS.RESTAdapter.extend({
sortQueryParams: function(params) {
var sortedKeys = Object.keys(params).sort().reverse();
var len = sortedKeys.length, newParams = {};
for (var i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
});
```
@method sortQueryParams
@param {Object} obj
@return {Object}
*/
sortQueryParams: function(obj) {
var keys = Ember.keys(obj);
var len = keys.length;
if (len < 2) {
return obj;
}
var newQueryParams = {};
var sortedKeys = keys.sort();
for (var i = 0; i < len; i++) {
newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]];
}
return newQueryParams;
},
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.find('comment', 1);
store.find('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```javascript
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```javascript
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API
key. Arbitrary headers can be set as key/value pairs on the
`RESTAdapter`'s `headers` object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@param {DS.Model} record
@return {Promise} promise
*/
find: function(store, type, id, record) {
return this.ajax(this.buildURL(type.typeKey, id, record), 'GET');
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type, sinceToken) {
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@return {Promise} promise
*/
findQuery: function(store, type, query) {
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@param {Array} records
@return {Promise} promise
*/
findMany: function(store, type, ids, records) {
return this.ajax(this.buildURL(type.typeKey, ids, records), 'GET', { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
If the URL is host-relative (starting with a single slash), the
request will use the host specified on the adapter (if any).
@method findHasMany
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@return {Promise} promise
*/
findHasMany: function(store, record, url, relationship) {
var host = ember$data$lib$adapters$rest_adapter$$get(this, 'host');
var id = ember$data$lib$adapters$rest_adapter$$get(record, 'id');
var type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@return {Promise} promise
*/
findBelongsTo: function(store, record, url, relationship) {
var id = ember$data$lib$adapters$rest_adapter$$get(record, 'id');
var type = record.constructor.typeKey;
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
var snapshot = record._createSnapshot();
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return this.ajax(this.buildURL(type.typeKey, null, record), "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
var snapshot = record._createSnapshot();
serializer.serializeIntoHash(data, type, snapshot);
var id = ember$data$lib$adapters$rest_adapter$$get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id, record), "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
var id = ember$data$lib$adapters$rest_adapter$$get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id, record), "DELETE");
},
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
@method buildURL
@param {String} type
@param {String} id
@param {DS.Model} record
@return {String} url
*/
buildURL: function(type, id, record) {
var url = [];
var host = ember$data$lib$adapters$rest_adapter$$get(this, 'host');
var prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
//We might get passed in an array of ids from findMany
//in which case we don't want to modify the url, as the
//ids will be passed in through a query param
if (id && !Ember.isArray(id)) { url.push(encodeURIComponent(id)); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentUrl
@return {String} urlPrefix
*/
urlPrefix: function(path, parentURL) {
var host = ember$data$lib$adapters$rest_adapter$$get(this, 'host');
var namespace = ember$data$lib$adapters$rest_adapter$$get(this, 'namespace');
var url = [];
if (path) {
// Protocol relative url
//jscs:disable disallowEmptyBlocks
if (/^\/\//.test(path)) {
// Do nothing, the full host is already included. This branch
// avoids the absolute path logic and the relative path logic.
// Absolute path
} else if (path.charAt(0) === '/') {
//jscs:enable disallowEmptyBlocks
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
}
if (path) {
url.push(path);
}
return url.join('/');
},
_stripIDFromURL: function(store, record) {
var type = record.constructor;
var url = this.buildURL(type.typeKey, record.get('id'), record);
var expandedURL = url.split('/');
//Case when the url is of the format ...something/:id
var lastSegment = expandedURL[expandedURL.length - 1];
var id = record.get('id');
if (lastSegment === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (ember$data$lib$adapters$rest_adapter$$endsWith(lastSegment, '?id=' + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join('/');
},
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
maxUrlLength: 2048,
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
This implementation groups together records that have the same base URL but
differing ids. For example `/comments/1` and `/comments/2` will be grouped together
because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2`
It also supports urls where ids are passed as a query param, such as `/comments?id=1`
but not those where there is more than 1 query param such as `/comments?id=2&name=David`
Currently only the query param of `id` is supported. If you need to support others, please
override this or the `_stripIDFromURL` method.
It does not group records that have differing base urls, such as for example: `/posts/1/comments/2`
and `/posts/2/comments/3`
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} records
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, records) {
var groups = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function() { return []; } });
var adapter = this;
var maxUrlLength = this.maxUrlLength;
ember$data$lib$adapters$rest_adapter$$forEach.call(records, function(record) {
var baseUrl = adapter._stripIDFromURL(store, record);
groups.get(baseUrl).push(record);
});
function splitGroupToFitInUrl(group, maxUrlLength, paramNameLength) {
var baseUrl = adapter._stripIDFromURL(store, group[0]);
var idsSize = 0;
var splitGroups = [[]];
ember$data$lib$adapters$rest_adapter$$forEach.call(group, function(record) {
var additionalLength = encodeURIComponent(record.get('id')).length + paramNameLength;
if (baseUrl.length + idsSize + additionalLength >= maxUrlLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
var lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(record);
});
return splitGroups;
}
var groupsArray = [];
groups.forEach(function(group, key) {
var paramNameLength = '&ids%5B%5D='.length;
var splitGroups = splitGroupToFitInUrl(group, maxUrlLength, paramNameLength);
ember$data$lib$adapters$rest_adapter$$forEach.call(splitGroups, function(splitGroup) {
groupsArray.push(splitGroup);
});
});
return groupsArray;
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```js
App.ApplicationAdapter = DS.RESTAdapter.extend({
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
}
});
```
@method pathForType
@param {String} type
@return {String} path
**/
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return Ember.String.pluralize(camelized);
},
/**
Takes an ajax response, and returns an error payload.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record.
This function should return the entire payload as received from the
server. Error object extraction and normalization of model errors
should be performed by `extractErrors` on the serializer.
Example
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@param {Object} responseText
@return {Object} jqXHR
*/
ajaxError: function(jqXHR, responseText, errorThrown) {
var isObject = jqXHR !== null && typeof jqXHR === 'object';
if (isObject) {
jqXHR.then = null;
if (!jqXHR.errorThrown) {
if (typeof errorThrown === 'string') {
jqXHR.errorThrown = new Error(errorThrown);
} else {
jqXHR.errorThrown = errorThrown;
}
}
}
return jqXHR;
},
/**
Takes an ajax response, and returns the json payload.
By default this hook just returns the jsonPayload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the request headers.
If you need to access these, you can override this hook to copy them
from jqXHR to the payload object so they can be processed in you serializer.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object. You can return a DS.InvalidError from
this hook and it will automatically reject the promise and put your record
into the invalid state.
@method ajaxSuccess
@param {Object} jqXHR
@param {Object} jsonPayload
@return {Object} jsonPayload
*/
ajaxSuccess: function(jqXHR, jsonPayload) {
return jsonPayload;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Promise} promise
*/
ajax: function(url, type, options) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var hash = adapter.ajaxOptions(url, type, options);
hash.success = function(json, textStatus, jqXHR) {
json = adapter.ajaxSuccess(jqXHR, json);
if (json instanceof ember$data$lib$system$adapter$$InvalidError) {
Ember.run(null, reject, json);
} else {
Ember.run(null, resolve, json);
}
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown));
};
Ember.$.ajax(hash);
}, 'DS: RESTAdapter#ajax ' + type + ' to ' + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Object}
*/
ajaxOptions: function(url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
var headers = ember$data$lib$adapters$rest_adapter$$get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
ember$data$lib$adapters$rest_adapter$$forEach.call(Ember.keys(headers), function(key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function ember$data$lib$adapters$rest_adapter$$endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== 'function') {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
var ember$inflector$lib$system$inflector$$capitalize = Ember.String.capitalize;
var ember$inflector$lib$system$inflector$$BLANK_REGEX = /^\s*$/;
var ember$inflector$lib$system$inflector$$LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/;
var ember$inflector$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/;
var ember$inflector$lib$system$inflector$$CAMELIZED_REGEX = /[A-Z][a-z\d]*$/;
function ember$inflector$lib$system$inflector$$loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function ember$inflector$lib$system$inflector$$loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
//pluralizing
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregular[pair[1].toLowerCase()] = pair[1];
//singularizing
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
rules.irregularInverse[pair[0].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow'); //=> 'kine'
inflector.singularize('kine'); //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice'); // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice'); // => 'advice'
inflector.pluralize('formula'); // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula'); // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function ember$inflector$lib$system$inflector$$Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || ember$inflector$lib$system$inflector$$makeDictionary();
ruleSet.irregularPairs = ruleSet.irregularPairs || ember$inflector$lib$system$inflector$$makeDictionary();
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: ember$inflector$lib$system$inflector$$makeDictionary(),
irregularInverse: ember$inflector$lib$system$inflector$$makeDictionary(),
uncountable: ember$inflector$lib$system$inflector$$makeDictionary()
};
ember$inflector$lib$system$inflector$$loadUncountable(rules, ruleSet.uncountable);
ember$inflector$lib$system$inflector$$loadIrregular(rules, ruleSet.irregularPairs);
this.enableCache();
}
if (!Object.create && !Object.create(null).hasOwnProperty) {
throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg");
}
function ember$inflector$lib$system$inflector$$makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
ember$inflector$lib$system$inflector$$Inflector.prototype = {
/**
@public
As inflections can be costly, and commonly the same subset of words are repeatedly
inflected an optional cache is provided.
@method enableCache
*/
enableCache: function() {
this.purgeCache();
this.singularize = function(word) {
this._cacheUsed = true;
return this._sCache[word] || (this._sCache[word] = this._singularize(word));
};
this.pluralize = function(word) {
this._cacheUsed = true;
return this._pCache[word] || (this._pCache[word] = this._pluralize(word));
};
},
/**
@public
@method purgedCache
*/
purgeCache: function() {
this._cacheUsed = false;
this._sCache = ember$inflector$lib$system$inflector$$makeDictionary();
this._pCache = ember$inflector$lib$system$inflector$$makeDictionary();
},
/**
@public
disable caching
@method disableCache;
*/
disableCache: function() {
this._sCache = null;
this._pCache = null;
this.singularize = function(word) {
return this._singularize(word);
};
this.pluralize = function(word) {
return this._pluralize(word);
};
},
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function(regex, string) {
if (this._cacheUsed) { this.purgeCache(); }
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function(regex, string) {
if (this._cacheUsed) { this.purgeCache(); }
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function(string) {
if (this._cacheUsed) { this.purgeCache(); }
ember$inflector$lib$system$inflector$$loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
if (this._cacheUsed) { this.purgeCache(); }
ember$inflector$lib$system$inflector$$loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function(word) {
return this._pluralize(word);
},
_pluralize: function(word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function(word) {
return this._singularize(word);
},
_singularize: function(word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function(word, typeRules, irregular) {
var inflection, substitution, result, lowercase, wordSplit,
firstPhrase, lastWord, isBlank, isCamelized, isUncountable,
isIrregular, isIrregularInverse, rule;
isBlank = ember$inflector$lib$system$inflector$$BLANK_REGEX.test(word);
isCamelized = ember$inflector$lib$system$inflector$$CAMELIZED_REGEX.test(word);
firstPhrase = "";
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
wordSplit = ember$inflector$lib$system$inflector$$LAST_WORD_DASHED_REGEX.exec(word) || ember$inflector$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX.exec(word);
if (wordSplit){
firstPhrase = wordSplit[1];
lastWord = wordSplit[2].toLowerCase();
}
isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord];
if (isUncountable) {
return word;
}
isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]);
if (isIrregular) {
if (irregular[lowercase]){
return isIrregular;
}
else {
isIrregular = (isCamelized) ? ember$inflector$lib$system$inflector$$capitalize(isIrregular) : isIrregular;
return firstPhrase + isIrregular;
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i-1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
var ember$inflector$lib$system$inflector$$default = ember$inflector$lib$system$inflector$$Inflector;
function ember$inflector$lib$system$string$$pluralize(word) {
return ember$inflector$lib$system$inflector$$default.inflector.pluralize(word);
}
function ember$inflector$lib$system$string$$singularize(word) {
return ember$inflector$lib$system$inflector$$default.inflector.singularize(word);
}
var ember$inflector$lib$system$inflections$$default = {
plurals: [
[/$/, 's'],
[/s$/i, 's'],
[/^(ax|test)is$/i, '$1es'],
[/(octop|vir)us$/i, '$1i'],
[/(octop|vir)i$/i, '$1i'],
[/(alias|status)$/i, '$1es'],
[/(bu)s$/i, '$1ses'],
[/(buffal|tomat)o$/i, '$1oes'],
[/([ti])um$/i, '$1a'],
[/([ti])a$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
[/(hive)$/i, '$1s'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/(x|ch|ss|sh)$/i, '$1es'],
[/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],
[/^(m|l)ouse$/i, '$1ice'],
[/^(m|l)ice$/i, '$1ice'],
[/^(ox)$/i, '$1en'],
[/^(oxen)$/i, '$1'],
[/(quiz)$/i, '$1zes']
],
singular: [
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(n)ews$/i, '$1ews'],
[/([ti])a$/i, '$1um'],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],
[/(^analy)(sis|ses)$/i, '$1sis'],
[/([^f])ves$/i, '$1fe'],
[/(hive)s$/i, '$1'],
[/(tive)s$/i, '$1'],
[/([lr])ves$/i, '$1f'],
[/([^aeiouy]|qu)ies$/i, '$1y'],
[/(s)eries$/i, '$1eries'],
[/(m)ovies$/i, '$1ovie'],
[/(x|ch|ss|sh)es$/i, '$1'],
[/^(m|l)ice$/i, '$1ouse'],
[/(bus)(es)?$/i, '$1'],
[/(o)es$/i, '$1'],
[/(shoe)s$/i, '$1'],
[/(cris|test)(is|es)$/i, '$1is'],
[/^(a)x[ie]s$/i, '$1xis'],
[/(octop|vir)(us|i)$/i, '$1us'],
[/(alias|status)(es)?$/i, '$1'],
[/^(ox)en/i, '$1'],
[/(vert|ind)ices$/i, '$1ex'],
[/(matr)ices$/i, '$1ix'],
[/(quiz)zes$/i, '$1'],
[/(database)s$/i, '$1']
],
irregularPairs: [
['person', 'people'],
['man', 'men'],
['child', 'children'],
['sex', 'sexes'],
['move', 'moves'],
['cow', 'kine'],
['zombie', 'zombies']
],
uncountable: [
'equipment',
'information',
'rice',
'money',
'species',
'series',
'fish',
'sheep',
'jeans',
'police'
]
};
ember$inflector$lib$system$inflector$$default.inflector = new ember$inflector$lib$system$inflector$$default(ember$inflector$lib$system$inflections$$default);
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* singularize a word. For example, turn "oxen" into "ox".
*
* Example:
*
* {{singularize myProperty}}
* {{singularize "oxen"}}
*
* @for Ember.Handlebars.helpers
* @method singularize
* @param {String|Property} word word to singularize
*/
Ember.Handlebars.helper('singularize', ember$inflector$lib$system$string$$singularize);
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* pluralize a word. For example, turn "ox" into "oxen".
*
* Example:
*
* {{pluralize count myProperty}}
* {{pluralize 1 "oxen"}}
* {{pluralize myProperty}}
* {{pluralize "ox"}}
*
* @for Ember.Handlebars.helpers
* @method pluralize
* @param {Number|Property} [count] count of objects
* @param {String|Property} word word to pluralize
*/
Ember.Handlebars.helper('pluralize', function(count, word, options) {
if(arguments.length < 3) {
return ember$inflector$lib$system$string$$pluralize(count);
} else {
/* jshint eqeqeq: false */
if(count != 1) {
/* jshint eqeqeq: true */
word = ember$inflector$lib$system$string$$pluralize(word);
}
return count + " " + word;
}
});
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function() {
return ember$inflector$lib$system$string$$pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function() {
return ember$inflector$lib$system$string$$singularize(this);
};
}
ember$inflector$lib$system$inflector$$default.defaultRules = ember$inflector$lib$system$inflections$$default;
Ember.Inflector = ember$inflector$lib$system$inflector$$default;
Ember.String.pluralize = ember$inflector$lib$system$string$$pluralize;
Ember.String.singularize = ember$inflector$lib$system$string$$singularize;
var ember$inflector$lib$main$$default = ember$inflector$lib$system$inflector$$default;
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active_model_adapter$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active_model_adapter$$underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
Unlike the DS.RESTAdapter, async relationship keys must be the singular form
of the relationship name, followed by "_id" for DS.belongsTo relationships,
or "_ids" for DS.hasMany relationships.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
**/
var activemodel$adapter$lib$system$active_model_adapter$$ActiveModelAdapter = ember$data$lib$adapters$rest_adapter$$default.extend({
defaultSerializer: '-active-model',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} type
@return String
*/
pathForType: function(type) {
var decamelized = activemodel$adapter$lib$system$active_model_adapter$$decamelize(type);
var underscored = activemodel$adapter$lib$system$active_model_adapter$$underscore(decamelized);
return ember$inflector$lib$system$string$$pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param {Object} jqXHR
@return error
*/
ajaxError: function(jqXHR) {
var error = this._super.apply(this, arguments);
if (jqXHR && jqXHR.status === 422) {
return new ember$data$lib$system$adapter$$InvalidError(Ember.$.parseJSON(jqXHR.responseText));
} else {
return error;
}
}
});
var activemodel$adapter$lib$system$active_model_adapter$$default = activemodel$adapter$lib$system$active_model_adapter$$ActiveModelAdapter;
/**
@module ember-data
*/
/**
`DS.Serializer` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `extract()`
* `serialize()`
And you can optionally override the following methods:
* `normalize()`
For an example implementation, see
[DS.JSONSerializer](DS.JSONSerializer.html), the included JSON serializer.
@class Serializer
@namespace DS
@extends Ember.Object
*/
var ember$data$lib$system$serializer$$Serializer = Ember.Object.extend({
/**
The `extract` method is used to deserialize the payload received from your
data source into the form that Ember Data expects.
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object}
*/
extract: Ember.required(Function),
/**
The `serialize` method is used when a record is saved in order to convert
the record into the form that your external data source expects.
`serialize` takes an optional `options` hash with a single option:
- `includeId`: If this is `true`, `serialize` should include the ID
in the serialized object it builds.
@method serialize
@param {subclass of DS.Model} record
@param {Object} [options]
@return {Object}
*/
serialize: Ember.required(Function),
/**
The `normalize` method is used to convert a payload received from your
external data source into the normalized form `store.push()` expects. You
should override this method, munge the hash and return the normalized
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
return hash;
}
});
var ember$data$lib$system$serializer$$default = ember$data$lib$system$serializer$$Serializer;
var ember$data$lib$serializers$json_serializer$$get = Ember.get;
var ember$data$lib$serializers$json_serializer$$isNone = Ember.isNone;
var ember$data$lib$serializers$json_serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$json_serializer$$merge = Ember.merge;
var ember$data$lib$serializers$json_serializer$$default = ember$data$lib$system$serializer$$default.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```javascript
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: {key: 'career'}
}
});
```
You can also remove attributes by setting the `serialize` key to
false in your mapping object.
Example
```javascript
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: {serialize: false},
occupation: {key: 'career'}
}
});
```
When serialized:
```javascript
{
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function applyTransform(key, type) {
if (!data.hasOwnProperty(key)) { return; }
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
this.applyTransforms(type, hash);
return hash;
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalizePayload: function(payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {Object} payload
@return {Object} the normalized payload
*/
normalizePayload: function(payload) {
return payload;
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = ember$data$lib$serializers$json_serializer$$get(this, 'attrs');
var payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = this._getMappedKey(key);
if (!hash.hasOwnProperty(payloadKey)) { continue; }
if (payloadKey !== key) {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = ember$data$lib$serializers$json_serializer$$get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeErrors
@private
*/
normalizeErrors: function(type, hash) {
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey: function(key) {
var attrs = ember$data$lib$serializers$json_serializer$$get(this, 'attrs');
var mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the {title: 'post_title'} and
//{title: {key: 'post_title'}} forms
if (mappedKey.key) {
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string') {
key = mappedKey;
}
}
return key;
},
/**
Check attrs.key.serialize property to inform if the `key`
can be serialized
@method _canSerialize
@private
@param {String} key
@return {boolean} true if the key can be serialized
*/
_canSerialize: function(key) {
var attrs = ember$data$lib$serializers$json_serializer$$get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function(snapshot, options) {
var json = {};
if (options && options.includeId) {
var id = snapshot.id;
if (id) {
json[ember$data$lib$serializers$json_serializer$$get(this, 'primaryKey')] = id;
}
}
snapshot.eachAttribute(function(key, attribute) {
this.serializeAttribute(snapshot, json, key, attribute);
}, this);
snapshot.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(snapshot, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(snapshot, json, relationship);
}
}, this);
return json;
},
/**
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, snapshot, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(snapshot, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function(hash, type, snapshot, options) {
ember$data$lib$serializers$json_serializer$$merge(hash, this.serialize(snapshot, options));
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all your attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(snapshot, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(snapshot, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Snapshot} snapshot
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(snapshot, json, key, attribute) {
var type = attribute.type;
if (this._canSerialize(key)) {
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key);
}
json[payloadKey] = value;
}
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsToId = snapshot.belongsTo(key, { id: true });
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "belongsTo");
}
//Need to check whether the id is there for new&async records
if (ember$data$lib$serializers$json_serializer$$isNone(belongsToId)) {
json[payloadKey] = null;
} else {
json[payloadKey] = belongsToId;
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(snapshot, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "hasMany");
}
var relationshipType = snapshot.type.determineRelationshipType(relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[payloadKey] = snapshot.hasMany(key, { ids: true });
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key,
belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
if (Ember.isNone(belongsTo)) {
json[key + "_type"] = null;
} else {
json[key + "_type"] = belongsTo.typeKey;
}
}
});
```
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
To override this method with a custom one, make sure to call
`this._super(store, type, payload, id, requestType)` with your
pre-processed data.
Here's an example of using `extract` manually:
```javascript
socket.on('message', function(message) {
var data = message.data;
var type = store.modelFor(message.modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, data.id, 'single');
store.push(message.modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindAll: function(store, type, payload, id, requestType) {
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function(store, type, payload, id, requestType) {
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindMany: function(store, type, payload, id, requestType) {
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function(store, type, payload, id, requestType) {
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Model#save` and the record is new. By default
this method is alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractCreateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been updated.
By default this method is alias for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been deleted.
By default this method is alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFind: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSave: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload, id, requestType) {
payload = this.normalizePayload(payload);
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(store, type, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, arrayPayload, id, requestType) {
var normalizedPayload = this.normalizePayload(arrayPayload);
var serializer = this;
return ember$data$lib$serializers$json_serializer$$map.call(normalizedPayload, function(singlePayload) {
return serializer.normalize(type, singlePayload);
});
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.setMetadataFor(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.setMetadataFor(type, payload.meta);
delete payload.meta;
}
},
/**
`extractErrors` is used to extract model errors when a call is made
to `DS.Model#save` which fails with an `InvalidError`. By default
Ember Data expects error information to be located on the `errors`
property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractErrors: function(store, type, payload, id) {
if (payload && typeof payload === 'object' && payload._problems) {
payload = payload._problems;
this.normalizeErrors(type, payload);
}
return payload;
}
});
```
@method extractErrors
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@return {Object} json The deserialized errors
*/
extractErrors: function(store, type, payload, id) {
if (payload && typeof payload === 'object' && payload.errors) {
payload = payload.errors;
this.normalizeErrors(type, payload);
}
return payload;
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```javascript
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@return {String} normalized key
*/
keyForAttribute: function(key) {
return key;
},
/**
`keyForRelationship` can be used to define a custom key when
serializing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
keyForRelationship: function(key, type) {
return key;
},
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
var ember$data$lib$serializers$rest_serializer$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$serializers$rest_serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$rest_serializer$$camelize = Ember.String.camelize;
function ember$data$lib$serializers$rest_serializer$$coerceId(id) {
return id == null ? null : id + '';
}
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to define
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, and the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var ember$data$lib$serializers$rest_serializer$$RESTSerializer = ember$data$lib$serializers$json_serializer$$default.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```javascript
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```js
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@return {Object}
*/
normalize: function(type, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
this.applyTransforms(type, hash);
return hash;
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, type, payload, id) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, type, payload, id);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} primaryType
@param {Object} payload
@param {String} recordId
@return {Object} the primary response to the original request
*/
extractSingle: function(store, primaryType, rawPayload, recordId) {
var payload = this.normalizePayload(rawPayload);
var primaryTypeName = primaryType.typeKey;
var primaryRecord;
for (var prop in payload) {
var typeName = this.typeForRoot(prop);
if (!store.modelFactoryFor(typeName)) {
Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false);
continue;
}
var type = store.modelFor(typeName);
var isPrimary = type.typeKey === primaryTypeName;
var value = payload[prop];
if (value === null) {
continue;
}
// legacy support for singular resources
if (isPrimary && Ember.typeOf(value) !== "array" ) {
primaryRecord = this.normalize(primaryType, value, prop);
continue;
}
/*jshint loopfunc:true*/
ember$data$lib$serializers$rest_serializer$$forEach.call(value, function(hash) {
var typeName = this.typeForRoot(prop);
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
hash = typeSerializer.normalize(type, hash, prop);
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord;
var isUpdatedRecord = isPrimary && ember$data$lib$serializers$rest_serializer$$coerceId(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(typeName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi"
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
});
payload = { comments: comments, posts: payload };
return this._super(store, type, payload);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} primaryType
@param {Object} payload
@return {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function(store, primaryType, rawPayload) {
var payload = this.normalizePayload(rawPayload);
var primaryTypeName = primaryType.typeKey;
var primaryArray;
for (var prop in payload) {
var typeKey = prop;
var forcedSecondary = false;
if (prop.charAt(0) === '_') {
forcedSecondary = true;
typeKey = prop.substr(1);
}
var typeName = this.typeForRoot(typeKey);
if (!store.modelFactoryFor(typeName)) {
Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false);
continue;
}
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName));
/*jshint loopfunc:true*/
var normalizedArray = ember$data$lib$serializers$rest_serializer$$map.call(payload[prop], function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function(store, rawPayload) {
var payload = this.normalizePayload(rawPayload);
for (var prop in payload) {
var typeName = this.typeForRoot(prop);
if (!store.modelFactoryFor(typeName, prop)) {
Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false);
continue;
}
var type = store.modelFor(typeName);
var typeSerializer = store.serializerFor(type);
/*jshint loopfunc:true*/
var normalizedArray = ember$data$lib$serializers$rest_serializer$$map.call(Ember.makeArray(payload[prop]), function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
store.pushMany(typeName, normalizedArray);
}
},
/**
This method is used to convert each JSON root key in the payload
into a typeKey that it can use to look up the appropriate model for
that part of the payload. By default the typeKey for a model is its
name in camelCase, so if your JSON root key is 'fast-car' you would
use typeForRoot to convert it to 'fastCar' so that Ember Data finds
the `FastCar` model.
If you diverge from this norm you should also consider changes to
store._normalizeTypeKey as well.
For example, your server may return prefixed root keys like so:
```js
{
"response-fast-car": {
"id": "1",
"name": "corvette"
}
}
```
In order for Ember Data to know that the model corresponding to
the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'),
you can override typeForRoot to convert 'response-fast-car' to
'fastCar' like so:
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
typeForRoot: function(root) {
// 'response-fast-car' should become 'fast-car'
var subRoot = root.substring(9);
// _super normalizes 'fast-car' to 'fastCar'
return this._super(subRoot);
}
});
```
@method typeForRoot
@param {String} key
@return {String} the model's typeKey
*/
typeForRoot: function(key) {
return ember$data$lib$serializers$rest_serializer$$camelize(ember$inflector$lib$system$string$$singularize(key));
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```js
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super(snapshot, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function(snapshot, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends the typeKey of a model, which is a camelized
version of the name.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function(hash, type, snapshot, options) {
hash[type.typeKey] = this.serialize(snapshot, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
if (Ember.isNone(belongsTo)) {
json[key + "Type"] = null;
} else {
json[key + "Type"] = Ember.String.camelize(belongsTo.typeKey);
}
}
});
Ember.runInDebug(function() {
ember$data$lib$serializers$rest_serializer$$RESTSerializer.reopen({
warnMessageNoModelForKey: function(prop, typeKey) {
return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.typeForRoot("' + prop + '"))';
}
});
});
var ember$data$lib$serializers$rest_serializer$$default = ember$data$lib$serializers$rest_serializer$$RESTSerializer;
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active_model_serializer$$forEach = Ember.EnumerableUtils.forEach;
var activemodel$adapter$lib$system$active_model_serializer$$camelize = Ember.String.camelize;
var activemodel$adapter$lib$system$active_model_serializer$$capitalize = Ember.String.capitalize;
var activemodel$adapter$lib$system$active_model_serializer$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active_model_serializer$$underscore = Ember.String.underscore;
/**
The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This serializer extends the DS.RESTSerializer by making consistent
use of the camelization, decamelization and pluralization methods to
normalize the serialized JSON into a format that is compatible with
a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelSerializer expects the JSON returned from your server
to follow the REST adapter conventions substituting underscored keys
for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelSerializer
@namespace DS
@extends DS.RESTSerializer
*/
var activemodel$adapter$lib$system$active_model_serializer$$ActiveModelSerializer = ember$data$lib$serializers$rest_serializer$$default.extend({
// SERIALIZE
/**
Converts camelCased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@return String
*/
keyForAttribute: function(attr) {
return activemodel$adapter$lib$system$active_model_serializer$$decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} key
@param {String} kind
@return String
*/
keyForRelationship: function(rawKey, kind) {
var key = activemodel$adapter$lib$system$active_model_serializer$$decamelize(rawKey);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return ember$inflector$lib$system$string$$singularize(key) + "_ids";
} else {
return key;
}
},
/*
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function(data, type, snapshot, options) {
var root = activemodel$adapter$lib$system$active_model_serializer$$underscore(activemodel$adapter$lib$system$active_model_serializer$$decamelize(type.typeKey));
data[root] = this.serialize(snapshot, options);
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = activemodel$adapter$lib$system$active_model_serializer$$underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = activemodel$adapter$lib$system$active_model_serializer$$capitalize(activemodel$adapter$lib$system$active_model_serializer$$camelize(belongsTo.typeKey));
}
},
// EXTRACT
/**
Add extra step to `DS.RESTSerializer.normalize` so links are normalized.
If your payload looks like:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@return Object
*/
normalize: function(type, hash, prop) {
this.normalizeLinks(hash);
return this._super(type, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
*/
normalizeLinks: function(data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = activemodel$adapter$lib$system$active_model_serializer$$camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
var payloadKey, payload;
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key);
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.typeForRoot(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
activemodel$adapter$lib$system$active_model_serializer$$forEach(payload, function(single) {
single.type = self.typeForRoot(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (!hash.hasOwnProperty(payloadKey)) { return; }
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
}
});
var activemodel$adapter$lib$system$active_model_serializer$$default = activemodel$adapter$lib$system$active_model_serializer$$ActiveModelSerializer;
/**
This is used internally to enable deprecation of container paths and provide
a decent message to the user indicating how to fix the issue.
@class ContainerProxy
@namespace DS
@private
*/
function ember$data$lib$system$container_proxy$$ContainerProxy(container) {
this.container = container;
}
ember$data$lib$system$container_proxy$$ContainerProxy.prototype.aliasedFactory = function(path, preLookup) {
var _this = this;
return {
create: function() {
if (preLookup) { preLookup(); }
return _this.container.lookup(path);
}
};
};
ember$data$lib$system$container_proxy$$ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ember$data$lib$system$container_proxy$$ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) {
var preLookupCallback = function() {
Ember.deprecate("You tried to look up '" + deprecated + "', " +
"but this has been deprecated in favor of '" + valid + "'.", false);
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ember$data$lib$system$container_proxy$$ContainerProxy.prototype.registerDeprecations = function(proxyPairs) {
var i, proxyPair, deprecated, valid;
for (i = proxyPairs.length; i > 0; i--) {
proxyPair = proxyPairs[i - 1];
deprecated = proxyPair['deprecated'];
valid = proxyPair['valid'];
this.registerDeprecation(deprecated, valid);
}
};
var ember$data$lib$system$container_proxy$$default = ember$data$lib$system$container_proxy$$ContainerProxy;
function activemodel$adapter$lib$setup$container$$setupActiveModelAdapter(container, application) {
var proxy = new ember$data$lib$system$container_proxy$$default(container);
proxy.registerDeprecations([
{ deprecated: 'serializer:_ams', valid: 'serializer:-active-model' },
{ deprecated: 'adapter:_ams', valid: 'adapter:-active-model' }
]);
container.register('serializer:-active-model', activemodel$adapter$lib$system$active_model_serializer$$default);
container.register('adapter:-active-model', activemodel$adapter$lib$system$active_model_adapter$$default);
}
var activemodel$adapter$lib$setup$container$$default = activemodel$adapter$lib$setup$container$$setupActiveModelAdapter;
/**
@module ember-data
*/
/**
All Ember Data methods and functions are defined inside of this namespace.
@class DS
@static
*/
/**
@property VERSION
@type String
@default '1.0.0-beta.15'
@static
*/
/*jshint -W079 */
var ember$data$lib$core$$DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.15'
});
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', ember$data$lib$core$$DS.VERSION);
}
var ember$data$lib$core$$default = ember$data$lib$core$$DS;
var ember$data$lib$system$promise_proxies$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$promise_proxies$$get = Ember.get;
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise_proxies$$PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved, then the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise_proxies$$PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
var ember$data$lib$system$promise_proxies$$promiseObject = function(promise, label) {
return ember$data$lib$system$promise_proxies$$PromiseObject.create({
promise: ember$data$lib$system$promise_proxies$$Promise.resolve(promise, label)
});
};
var ember$data$lib$system$promise_proxies$$promiseArray = function(promise, label) {
return ember$data$lib$system$promise_proxies$$PromiseArray.create({
promise: ember$data$lib$system$promise_proxies$$Promise.resolve(promise, label)
});
};
/**
A PromiseManyArray is a PromiseArray that also proxies certain method calls
to the underlying manyArray.
Right now we proxy:
* `reload()`
* `createRecord()`
* `on()`
* `one()`
* `trigger()`
* `off()`
* `has()`
@class PromiseManyArray
@namespace DS
@extends Ember.ArrayProxy
*/
function ember$data$lib$system$promise_proxies$$proxyToContent(method) {
return function() {
var content = ember$data$lib$system$promise_proxies$$get(this, 'content');
return content[method].apply(content, arguments);
};
}
var ember$data$lib$system$promise_proxies$$PromiseManyArray = ember$data$lib$system$promise_proxies$$PromiseArray.extend({
reload: function() {
//I don't think this should ever happen right now, but worth guarding if we refactor the async relationships
Ember.assert('You are trying to reload an async manyArray before it has been created', ember$data$lib$system$promise_proxies$$get(this, 'content'));
return ember$data$lib$system$promise_proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise_proxies$$get(this, 'content').reload()
});
},
createRecord: ember$data$lib$system$promise_proxies$$proxyToContent('createRecord'),
on: ember$data$lib$system$promise_proxies$$proxyToContent('on'),
one: ember$data$lib$system$promise_proxies$$proxyToContent('one'),
trigger: ember$data$lib$system$promise_proxies$$proxyToContent('trigger'),
off: ember$data$lib$system$promise_proxies$$proxyToContent('off'),
has: ember$data$lib$system$promise_proxies$$proxyToContent('has')
});
var ember$data$lib$system$promise_proxies$$promiseManyArray = function(promise, label) {
return ember$data$lib$system$promise_proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise_proxies$$Promise.resolve(promise, label)
});
};
var ember$data$lib$system$record_arrays$record_array$$get = Ember.get;
var ember$data$lib$system$record_arrays$record_array$$set = Ember.set;
var ember$data$lib$system$record_arrays$record_array$$default = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function(index) {
var content = ember$data$lib$system$record_arrays$record_array$$get(this, 'content');
return content.objectAt(index);
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function() {
if (ember$data$lib$system$record_arrays$record_array$$get(this, 'isUpdating')) { return; }
var store = ember$data$lib$system$record_arrays$record_array$$get(this, 'store');
var type = ember$data$lib$system$record_arrays$record_array$$get(this, 'type');
return store.fetchAll(type, this);
},
/**
Adds a record to the `RecordArray` without duplicates
@method addRecord
@private
@param {DS.Model} record
@param {DS.Model} an optional index to insert at
*/
addRecord: function(record, idx) {
var content = ember$data$lib$system$record_arrays$record_array$$get(this, 'content');
if (idx === undefined) {
content.addObject(record);
} else if (!content.contains(record)) {
content.insertAt(idx, record);
}
},
_pushRecord: function(record) {
ember$data$lib$system$record_arrays$record_array$$get(this, 'content').pushObject(record);
},
/**
Adds a record to the `RecordArray`, but allows duplicates
@deprecated
@method pushRecord
@private
@param {DS.Model} record
*/
pushRecord: function(record) {
Ember.deprecate('Usage of `recordArray.pushRecord` is deprecated, use `recordArray.addObject` instead');
this._pushRecord(record);
},
/**
Removes a record to the `RecordArray`.
@method removeRecord
@private
@param {DS.Model} record
*/
removeRecord: function(record) {
ember$data$lib$system$record_arrays$record_array$$get(this, 'content').removeObject(record);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all('message');
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function() {
var recordArray = this;
var promiseLabel = "DS: RecordArray#save " + ember$data$lib$system$record_arrays$record_array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return recordArray;
}, null, "DS: RecordArray#save return RecordArray");
return ember$data$lib$system$promise_proxies$$PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function() {
var array = this;
this.forEach(function(record) {
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays["delete"](array);
}
});
},
/**
@method _unregisterFromManager
@private
*/
_unregisterFromManager: function() {
var manager = ember$data$lib$system$record_arrays$record_array$$get(this, 'manager');
//We will stop needing this stupid if statement soon, once manyArray are refactored to not be RecordArrays
if (manager) {
manager.unregisterFilteredRecordArray(this);
}
},
willDestroy: function() {
this._unregisterFromManager();
this._dissociateFromOwnRecords();
ember$data$lib$system$record_arrays$record_array$$set(this, 'content', undefined);
this._super.apply(this, arguments);
}
});
/**
@module ember-data
*/
var ember$data$lib$system$record_arrays$filtered_record_array$$get = Ember.get;
var ember$data$lib$system$record_arrays$filtered_record_array$$default = ember$data$lib$system$record_arrays$record_array$$default.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function() {
var type = ember$data$lib$system$record_arrays$filtered_record_array$$get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function() {
var manager = ember$data$lib$system$record_arrays$filtered_record_array$$get(this, 'manager');
manager.updateFilter(this, ember$data$lib$system$record_arrays$filtered_record_array$$get(this, 'type'), ember$data$lib$system$record_arrays$filtered_record_array$$get(this, 'filterFunction'));
},
updateFilter: Ember.observer(function() {
Ember.run.once(this, this._updateFilter);
}, 'filterFunction')
});
/**
@module ember-data
*/
var ember$data$lib$system$record_arrays$adapter_populated_record_array$$get = Ember.get;
function ember$data$lib$system$record_arrays$adapter_populated_record_array$$cloneNull(source) {
var clone = Ember.create(null);
for (var key in source) {
clone[key] = source[key];
}
return clone;
}
var ember$data$lib$system$record_arrays$adapter_populated_record_array$$default = ember$data$lib$system$record_arrays$record_array$$default.extend({
query: null,
replace: function() {
var type = ember$data$lib$system$record_arrays$adapter_populated_record_array$$get(this, 'type').toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function(data) {
var store = ember$data$lib$system$record_arrays$adapter_populated_record_array$$get(this, 'store');
var type = ember$data$lib$system$record_arrays$adapter_populated_record_array$$get(this, 'type');
var records = store.pushMany(type, data);
var meta = store.metadataFor(type);
this.setProperties({
content: Ember.A(records),
isLoaded: true,
meta: ember$data$lib$system$record_arrays$adapter_populated_record_array$$cloneNull(meta)
});
records.forEach(function(record) {
this.manager.recordArraysForRecord(record).add(this);
}, this);
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, 'trigger', 'didLoad');
}
});
var ember$data$lib$system$record_arrays$many_array$$get = Ember.get;
var ember$data$lib$system$record_arrays$many_array$$set = Ember.set;
var ember$data$lib$system$record_arrays$many_array$$default = Ember.Object.extend(Ember.MutableArray, Ember.Evented, {
init: function() {
this.currentState = Ember.A([]);
},
record: null,
canonicalState: null,
currentState: null,
length: 0,
objectAt: function(index) {
if (this.currentState[index]) {
return this.currentState[index];
} else {
return this.canonicalState[index];
}
},
flushCanonical: function() {
//TODO make this smarter, currently its plenty stupid
var toSet = this.canonicalState.slice(0);
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = this.currentState.filter(function(record) {
return record.get('isNew');
});
toSet = toSet.concat(newRecords);
var oldLength = this.length;
this.arrayContentWillChange(0, this.length, toSet.length);
this.set('length', toSet.length);
this.currentState = toSet;
this.arrayContentDidChange(0, oldLength, this.length);
//TODO Figure out to notify only on additions and maybe only if unloaded
this.relationship.notifyHasManyChanged();
this.record.updateRecordArrays();
},
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
/**
The loading state of this array
@property {Boolean} isLoaded
*/
isLoaded: false,
/**
The relationship which manages this array.
@property {ManyRelationship} relationship
@private
*/
relationship: null,
internalReplace: function(idx, amt, objects) {
if (!objects) {
objects = [];
}
this.arrayContentWillChange(idx, amt, objects.length);
this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
this.set('length', this.currentState.length);
this.arrayContentDidChange(idx, amt, objects.length);
if (objects) {
//TODO(Igor) probably needed only for unloaded records
this.relationship.notifyHasManyChanged();
}
this.record.updateRecordArrays();
},
//TODO(Igor) optimize
internalRemoveRecords: function(records) {
var index;
for (var i=0; i < records.length; i++) {
index = this.currentState.indexOf(records[i]);
this.internalReplace(index, 1);
}
},
//TODO(Igor) optimize
internalAddRecords: function(records, idx) {
if (idx === undefined) {
idx = this.currentState.length;
}
this.internalReplace(idx, 0, records);
},
replace: function(idx, amt, objects) {
var records;
if (amt > 0) {
records = this.currentState.slice(idx, idx+amt);
this.get('relationship').removeRecords(records);
}
if (objects) {
this.get('relationship').addRecords(objects, idx);
}
},
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function(count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function() {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
ember$data$lib$system$record_arrays$many_array$$set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method reload
@public
*/
reload: function() {
return this.relationship.reload();
},
/**
Saves all of the records in the `ManyArray`.
Example
```javascript
store.find('inbox', 1).then(function(inbox) {
inbox.get('messages').then(function(messages) {
messages.forEach(function(message) {
message.set('isRead', true);
});
messages.save()
});
});
```
@method save
@return {DS.PromiseArray} promise
*/
save: function() {
var manyArray = this;
var promiseLabel = "DS: ManyArray#save " + ember$data$lib$system$record_arrays$many_array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return manyArray;
}, null, "DS: ManyArray#save return ManyArray");
return ember$data$lib$system$promise_proxies$$PromiseArray.create({ promise: promise });
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function(hash) {
var store = ember$data$lib$system$record_arrays$many_array$$get(this, 'store');
var type = ember$data$lib$system$record_arrays$many_array$$get(this, 'type');
var record;
Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !ember$data$lib$system$record_arrays$many_array$$get(this, 'isPolymorphic'));
record = store.createRecord(type, hash);
this.pushObject(record);
return record;
},
/**
@method addRecord
@param {DS.Model} record
@deprecated Use `addObject()` instead
*/
addRecord: function(record) {
Ember.deprecate('Using manyArray.addRecord() has been deprecated. You should use manyArray.addObject() instead.');
this.addObject(record);
},
/**
@method removeRecord
@param {DS.Model} record
@deprecated Use `removeObject()` instead
*/
removeRecord: function(record) {
Ember.deprecate('Using manyArray.removeRecord() has been deprecated. You should use manyArray.removeObject() instead.');
this.removeObject(record);
}
});
var ember$data$lib$system$record_array_manager$$get = Ember.get;
var ember$data$lib$system$record_array_manager$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$record_array_manager$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$record_array_manager$$default = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function(record) {
if (this.changedRecords.push(record) !== 1) { return; }
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || ember$data$lib$system$map$$OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
ember$data$lib$system$record_array_manager$$forEach(this.changedRecords, function(record) {
if (ember$data$lib$system$record_array_manager$$get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
recordArrays.forEach(function(array) {
array.removeRecord(record);
});
record._recordArrays = null;
},
//Don't need to update non filtered arrays on simple changes
_recordWasChanged: function (record) {
var type = record.constructor;
var recordArrays = this.filteredRecordArrays.get(type);
var filter;
ember$data$lib$system$record_array_manager$$forEach(recordArrays, function(array) {
filter = ember$data$lib$system$record_array_manager$$get(array, 'filterFunction');
if (filter) {
this.updateRecordArray(array, filter, type, record);
}
}, this);
},
//Need to update live arrays on loading
recordWasLoaded: function(record) {
var type = record.constructor;
var recordArrays = this.filteredRecordArrays.get(type);
var filter;
ember$data$lib$system$record_array_manager$$forEach(recordArrays, function(array) {
filter = ember$data$lib$system$record_array_manager$$get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
if (!recordArrays.has(array)) {
array._pushRecord(record);
recordArrays.add(array);
}
} else if (!shouldBeInArray) {
recordArrays["delete"](array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param {Array} array
@param {String} type
@param {Function} filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type);
var records = typeMap.records;
var record;
for (var i = 0, l = records.length; i < l; i++) {
record = records[i];
if (!ember$data$lib$system$record_array_manager$$get(record, 'isDeleted') && !ember$data$lib$system$record_array_manager$$get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} type
@return {DS.RecordArray}
*/
createRecordArray: function(type) {
var array = ember$data$lib$system$record_arrays$record_array$$default.create({
type: type,
content: Ember.A(),
store: this.store,
isLoaded: true,
manager: this
});
this.registerFilteredRecordArray(array, type);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {Class} type
@param {Function} filter
@param {Object} query (optional
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function(type, filter, query) {
var array = ember$data$lib$system$record_arrays$filtered_record_array$$default.create({
query: query,
type: type,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, type, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {Class} type
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function(type, query) {
var array = ember$data$lib$system$record_arrays$adapter_populated_record_array$$default.create({
type: type,
query: query,
content: Ember.A(),
store: this.store,
manager: this
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
/**
Unregister a FilteredRecordArray.
So manager will not update this array.
@method unregisterFilteredRecordArray
@param {DS.RecordArray} array
*/
unregisterFilteredRecordArray: function(array) {
var recordArrays = this.filteredRecordArrays.get(array.type);
var index = ember$data$lib$system$record_array_manager$$indexOf(recordArrays, array);
recordArrays.splice(index, 1);
},
willDestroy: function() {
this._super.apply(this, arguments);
this.filteredRecordArrays.forEach(function(value) {
ember$data$lib$system$record_array_manager$$forEach(ember$data$lib$system$record_array_manager$$flatten(value), ember$data$lib$system$record_array_manager$$destroy);
});
ember$data$lib$system$record_array_manager$$forEach(this._adapterPopulatedRecordArrays, ember$data$lib$system$record_array_manager$$destroy);
}
});
function ember$data$lib$system$record_array_manager$$destroy(entry) {
entry.destroy();
}
function ember$data$lib$system$record_array_manager$$flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
/**
@module ember-data
*/
var ember$data$lib$system$model$states$$get = Ember.get;
var ember$data$lib$system$model$states$$set = Ember.set;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (This state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What that means is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function ember$data$lib$system$model$states$$didSetProperty(record, context) {
if (context.value === context.originalValue) {
delete record._attributes[context.name];
record.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
record.send('becomeDirty');
}
record.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
// failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var ember$data$lib$system$model$states$$DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
//TODO(Igor) reloading now triggers a
//loadingData event, though it seems fine?
loadingData: Ember.K,
propertyWasReset: function(record, name) {
var length = Ember.keys(record._attributes).length;
var stillDirty = length > 0;
if (!stillDirty) { record.send('rolledBack'); }
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function(record) {
record.transitionTo('inFlight');
},
reloadRecord: function(record, resolve) {
resolve(ember$data$lib$system$model$states$$get(record, 'store').reloadRecord(record));
},
rolledBack: function(record) {
record.transitionTo('loaded.saved');
},
becameInvalid: function(record) {
record.transitionTo('invalid');
},
rollback: function(record) {
record.rollback();
record.triggerLater('ready');
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: function(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false);
},
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
var dirtyType = ember$data$lib$system$model$states$$get(this, 'dirtyType');
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function(record) {
record.transitionTo('invalid');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// A record is in the `invalid` if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.disconnectRelationships();
},
didSetProperty: function(record, context) {
ember$data$lib$system$model$states$$get(record, 'errors').remove(context.name);
ember$data$lib$system$model$states$$didSetProperty(record, context);
},
becomeDirty: Ember.K,
willCommit: function(record) {
ember$data$lib$system$model$states$$get(record, 'errors').clear();
record.transitionTo('inFlight');
},
rolledBack: function(record) {
ember$data$lib$system$model$states$$get(record, 'errors').clear();
record.triggerLater('ready');
},
becameValid: function(record) {
record.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('becameInvalid', record);
},
exit: function(record) {
record._inFlightAttributes = {};
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function ember$data$lib$system$model$states$$deepClone(object) {
var clone = {};
var value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = ember$data$lib$system$model$states$$deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function ember$data$lib$system$model$states$$mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function ember$data$lib$system$model$states$$dirtyState(options) {
var newState = ember$data$lib$system$model$states$$deepClone(ember$data$lib$system$model$states$$DirtyState);
return ember$data$lib$system$model$states$$mixin(newState, options);
}
var ember$data$lib$system$model$states$$createdState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
ember$data$lib$system$model$states$$createdState.uncommitted.rolledBack = function(record) {
record.transitionTo('deleted.saved');
};
var ember$data$lib$system$model$states$$updatedState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'updated'
});
ember$data$lib$system$model$states$$createdState.uncommitted.deleteRecord = function(record) {
record.disconnectRelationships();
record.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.rollback = function(record) {
ember$data$lib$system$model$states$$DirtyState.uncommitted.rollback.apply(this, arguments);
record.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.pushedData = function(record) {
record.transitionTo('loaded.updated.uncommitted');
record.triggerLater('didLoad');
};
ember$data$lib$system$model$states$$createdState.uncommitted.propertyWasReset = Ember.K;
function ember$data$lib$system$model$states$$assertAgainstUnloadRecord(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false);
}
ember$data$lib$system$model$states$$updatedState.inFlight.unloadRecord = ember$data$lib$system$model$states$$assertAgainstUnloadRecord;
ember$data$lib$system$model$states$$updatedState.uncommitted.deleteRecord = function(record) {
record.transitionTo('deleted.uncommitted');
record.disconnectRelationships();
};
var ember$data$lib$system$model$states$$RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function(record, promise) {
record._loadingPromise = promise;
record.transitionTo('loading');
},
loadedData: function(record) {
record.transitionTo('loaded.created.uncommitted');
record.triggerLater('ready');
},
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
record.triggerLater('ready');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function(record) {
record._loadingPromise = null;
},
// EVENTS
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
record.triggerLater('ready');
ember$data$lib$system$model$states$$set(record, 'isError', false);
},
becameError: function(record) {
record.triggerLater('becameError', record);
},
notFound: function(record) {
record.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
//TODO(Igor) Reloading now triggers a loadingData event,
//but it should be ok?
loadingData: Ember.K,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function(record) {
var attrs = record._attributes;
var isDirty = Ember.keys(attrs).length > 0;
if (isDirty) {
record.adapterDidDirty();
}
},
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
pushedData: Ember.K,
becomeDirty: function(record) {
record.transitionTo('updated.uncommitted');
},
willCommit: function(record) {
record.transitionTo('updated.inFlight');
},
reloadRecord: function(record, resolve) {
resolve(ember$data$lib$system$model$states$$get(record, 'store').reloadRecord(record));
},
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.disconnectRelationships();
},
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
didCommit: function(record) {
record.send('invokeLifecycleCallbacks', ember$data$lib$system$model$states$$get(record, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: ember$data$lib$system$model$states$$createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: ember$data$lib$system$model$states$$updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function(record) {
record.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function(record) {
record.transitionTo('inFlight');
},
rollback: function(record) {
record.rollback();
record.triggerLater('ready');
},
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('ready');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function(record) {
var store = ember$data$lib$system$model$states$$get(record, 'store');
store._dematerializeRecord(record);
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('didDelete', record);
record.triggerLater('didCommit', record);
},
willCommit: Ember.K,
didCommit: Ember.K
}
},
invokeLifecycleCallbacks: function(record, dirtyType) {
if (dirtyType === 'created') {
record.triggerLater('didCreate', record);
} else {
record.triggerLater('didUpdate', record);
}
record.triggerLater('didCommit', record);
}
};
function ember$data$lib$system$model$states$$wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = ember$data$lib$system$model$states$$mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
if (typeof object[prop] === 'object') {
object[prop] = ember$data$lib$system$model$states$$wireState(object[prop], object, name + "." + prop);
}
}
return object;
}
ember$data$lib$system$model$states$$RootState = ember$data$lib$system$model$states$$wireState(ember$data$lib$system$model$states$$RootState, null, "root");
var ember$data$lib$system$model$states$$default = ember$data$lib$system$model$states$$RootState;
var ember$data$lib$system$model$errors$$get = Ember.get;
var ember$data$lib$system$model$errors$$isEmpty = Ember.isEmpty;
var ember$data$lib$system$model$errors$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$model$errors$$default = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function(target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed("content", {
initialValue: function() {
return ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function() {
return Ember.A();
}
});
},
addedItem: function(errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function(errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
```javascript
var user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save().catch(function(){
user.get('errors').errorsFor('email'); // returns:
// [{attribute: "email", message: "Doesn't look like a valid email."}]
});
```
@method errorsFor
@param {String} attribute
@return {Array}
*/
errorsFor: function(attribute) {
return ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName').get(attribute);
},
/**
An array containing all of the error messages for this
record. This is useful for displaying all errors to the user.
```handlebars
{{#each message in model.errors.messages}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property messages
@type {Array}
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function() {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function(attribute) {
var errors = this.errorsFor(attribute);
if (ember$data$lib$system$model$errors$$isEmpty(errors)) { return null; }
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function(index, previousObject, context) {
return ember$data$lib$system$model$errors$$get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
Example:
```javascript
if (!user.get('username') {
user.get('errors').add('username', 'This field is required');
}
```
@method add
@param {String} attribute
@param {Array|String} messages
*/
add: function(attribute, messages) {
var wasEmpty = ember$data$lib$system$model$errors$$get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
ember$data$lib$system$model$errors$$get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function(attribute, messages) {
var errors = this.errorsFor(attribute);
return ember$data$lib$system$model$errors$$map(Ember.makeArray(messages), function(message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
Example:
```javascript
App.User = DS.Model.extend({
email: DS.attr('string'),
twoFactorAuth: DS.attr('boolean'),
phone: DS.attr('string')
});
App.UserEditRoute = Ember.Route.extend({
actions: {
save: function(user) {
if (!user.get('twoFactorAuth')) {
user.get('errors').remove('phone');
}
user.save();
}
}
});
```
@method remove
@param {String} attribute
*/
remove: function(attribute) {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; }
var content = ember$data$lib$system$model$errors$$get(this, 'content').rejectBy('attribute', attribute);
ember$data$lib$system$model$errors$$get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
Example:
```javascript
App.UserEditRoute = Ember.Route.extend({
actions: {
retrySave: function(user) {
user.get('errors').clear();
user.save();
}
}
});
```
@method clear
*/
clear: function() {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; }
ember$data$lib$system$model$errors$$get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
```javascript
App.UserEditRoute = Ember.Route.extend({
actions: {
save: function(user) {
if (user.get('errors').has('email')) {
return alert('Please update your email before attempting to save.');
}
user.save();
}
}
});
```
@method has
@param {String} attribute
@return {Boolean} true if there some errors on given attribute
*/
has: function(attribute) {
return !ember$data$lib$system$model$errors$$isEmpty(this.errorsFor(attribute));
}
});
function ember$data$lib$system$merge$$merge(original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = Ember.keys(updates);
var prop;
var length = props.length;
for (var i = 0; i < length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
}
var ember$data$lib$system$merge$$default = ember$data$lib$system$merge$$merge;
var ember$data$lib$system$relationships$state$relationship$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$relationships$state$relationship$$Relationship = function(store, record, inverseKey, relationshipMeta) {
this.members = new ember$data$lib$system$map$$OrderedSet();
this.canonicalMembers = new ember$data$lib$system$map$$OrderedSet();
this.store = store;
this.key = relationshipMeta.key;
this.inverseKey = inverseKey;
this.record = record;
this.isAsync = relationshipMeta.options.async;
this.relationshipMeta = relationshipMeta;
//This probably breaks for polymorphic relationship in complex scenarios, due to
//multiple possible typeKeys
this.inverseKeyForImplicit = this.store.modelFor(this.record.constructor).typeKey + this.key;
this.linkPromise = null;
};
ember$data$lib$system$relationships$state$relationship$$Relationship.prototype = {
constructor: ember$data$lib$system$relationships$state$relationship$$Relationship,
destroy: Ember.K,
clear: function() {
var members = this.members.list;
var member;
while (members.length > 0) {
member = members[0];
this.removeRecord(member);
}
},
disconnect: function() {
this.members.forEach(function(member) {
this.removeRecordFromInverse(member);
}, this);
},
reconnect: function() {
this.members.forEach(function(member) {
this.addRecordToInverse(member);
}, this);
},
removeRecords: function(records) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function(record) {
self.removeRecord(record);
});
},
addRecords: function(records, idx) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function(record) {
self.addRecord(record, idx);
if (idx !== undefined) {
idx++;
}
});
},
addCanonicalRecords: function(records, idx) {
for (var i=0; i<records.length; i++) {
if (idx !== undefined) {
this.addCanonicalRecord(records[i], i+idx);
} else {
this.addCanonicalRecord(records[i]);
}
}
},
addCanonicalRecord: function(record, idx) {
if (!this.canonicalMembers.has(record)) {
this.canonicalMembers.add(record);
if (this.inverseKey) {
record._relationships[this.inverseKey].addCanonicalRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record);
}
}
this.flushCanonicalLater();
},
removeCanonicalRecords: function(records, idx) {
for (var i=0; i<records.length; i++) {
if (idx !== undefined) {
this.removeCanonicalRecord(records[i], i+idx);
} else {
this.removeCanonicalRecord(records[i]);
}
}
},
removeCanonicalRecord: function(record, idx) {
if (this.canonicalMembers.has(record)) {
this.removeCanonicalRecordFromOwn(record);
if (this.inverseKey) {
this.removeCanonicalRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record);
}
}
}
this.flushCanonicalLater();
},
addRecord: function(record, idx) {
if (!this.members.has(record)) {
this.members.add(record);
this.notifyRecordRelationshipAdded(record, idx);
if (this.inverseKey) {
record._relationships[this.inverseKey].addRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record);
}
this.record.updateRecordArraysLater();
}
},
removeRecord: function(record) {
if (this.members.has(record)) {
this.removeRecordFromOwn(record);
if (this.inverseKey) {
this.removeRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record);
}
}
}
},
addRecordToInverse: function(record) {
if (this.inverseKey) {
record._relationships[this.inverseKey].addRecord(this.record);
}
},
removeRecordFromInverse: function(record) {
var inverseRelationship = record._relationships[this.inverseKey];
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeRecordFromOwn(this.record);
}
},
removeRecordFromOwn: function(record) {
this.members["delete"](record);
this.notifyRecordRelationshipRemoved(record);
this.record.updateRecordArrays();
},
removeCanonicalRecordFromInverse: function(record) {
var inverseRelationship = record._relationships[this.inverseKey];
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeCanonicalRecordFromOwn(this.record);
}
},
removeCanonicalRecordFromOwn: function(record) {
this.canonicalMembers["delete"](record);
this.flushCanonicalLater();
},
flushCanonical: function() {
this.willSync = false;
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = [];
for (var i=0; i<this.members.list.length; i++) {
if (this.members.list[i].get('isNew')) {
newRecords.push(this.members.list[i]);
}
}
//TODO(Igor) make this less abysmally slow
this.members = this.canonicalMembers.copy();
for (i=0; i<newRecords.length; i++) {
this.members.add(newRecords[i]);
}
},
flushCanonicalLater: function() {
if (this.willSync) {
return;
}
this.willSync = true;
var self = this;
this.store._backburner.join(function() {
self.store._backburner.schedule('syncRelationships', self, self.flushCanonical);
});
},
updateLink: function(link) {
Ember.warn("You have pushed a record of type '" + this.record.constructor.typeKey + "' with '" + this.key + "' as a link, but the association is not an async relationship.", this.isAsync);
Ember.assert("You have pushed a record of type '" + this.record.constructor.typeKey + "' with '" + this.key + "' as a link, but the value of that link is not a string.", typeof link === 'string' || link === null);
if (link !== this.link) {
this.link = link;
this.linkPromise = null;
this.record.notifyPropertyChange(this.key);
}
},
findLink: function() {
if (this.linkPromise) {
return this.linkPromise;
} else {
var promise = this.fetchLink();
this.linkPromise = promise;
return promise.then(function(result) {
return result;
});
}
},
updateRecordsFromAdapter: function(records) {
//TODO(Igor) move this to a proper place
var self = this;
//TODO Once we have adapter support, we need to handle updated and canonical changes
self.computeChanges(records);
},
notifyRecordRelationshipAdded: Ember.K,
notifyRecordRelationshipRemoved: Ember.K
};
var ember$data$lib$system$relationships$state$relationship$$default = ember$data$lib$system$relationships$state$relationship$$Relationship;
var ember$data$lib$system$relationships$state$has_many$$ManyRelationship = function(store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.belongsToType = relationshipMeta.type;
this.canonicalState = [];
this.manyArray = ember$data$lib$system$record_arrays$many_array$$default.create({
canonicalState: this.canonicalState,
store: this.store,
relationship: this,
type: this.belongsToType,
record: record
});
this.isPolymorphic = relationshipMeta.options.polymorphic;
this.manyArray.isPolymorphic = this.isPolymorphic;
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.constructor = ember$data$lib$system$relationships$state$has_many$$ManyRelationship;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.destroy = function() {
this.manyArray.destroy();
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.addCanonicalRecord = function(record, idx) {
if (this.canonicalMembers.has(record)) {
return;
}
if (idx !== undefined) {
this.canonicalState.splice(idx, 0, record);
} else {
this.canonicalState.push(record);
}
this._super$addCanonicalRecord(record, idx);
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.addRecord = function(record, idx) {
if (this.members.has(record)) {
return;
}
this._super$addRecord(record, idx);
this.manyArray.internalAddRecords([record], idx);
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.removeCanonicalRecordFromOwn = function(record, idx) {
var i = idx;
if (!this.canonicalMembers.has(record)) {
return;
}
if (i === undefined) {
i = this.canonicalState.indexOf(record);
}
if (i > -1) {
this.canonicalState.splice(i, 1);
}
this._super$removeCanonicalRecordFromOwn(record, idx);
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.flushCanonical = function() {
this.manyArray.flushCanonical();
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.removeRecordFromOwn = function(record, idx) {
if (!this.members.has(record)) {
return;
}
this._super$removeRecordFromOwn(record, idx);
if (idx !== undefined) {
//TODO(Igor) not used currently, fix
this.manyArray.currentState.removeAt(idx);
} else {
this.manyArray.internalRemoveRecords([record]);
}
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.notifyRecordRelationshipAdded = function(record, idx) {
var type = this.relationshipMeta.type;
Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to the " + this.record.constructor.typeKey + "." + this.key + " relationship (only '" + this.belongsToType.typeKey + "' allowed)", (function () {
if (record instanceof type) {
return true;
} else if (Ember.MODEL_FACTORY_INJECTIONS) {
return record instanceof type.superclass;
}
return false;
})());
this.record.notifyHasManyAdded(this.key, record, idx);
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.reload = function() {
var self = this;
if (this.link) {
return this.fetchLink();
} else {
return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function() {
//Goes away after the manyArray refactor
self.manyArray.set('isLoaded', true);
return self.manyArray;
});
}
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.computeChanges = function(records) {
var members = this.canonicalMembers;
var recordsToRemove = [];
var length;
var record;
var i;
records = ember$data$lib$system$relationships$state$has_many$$setForArray(records);
members.forEach(function(member) {
if (records.has(member)) { return; }
recordsToRemove.push(member);
});
this.removeCanonicalRecords(recordsToRemove);
// Using records.toArray() since currently using
// removeRecord can modify length, messing stuff up
// forEach since it directly looks at "length" each
// iteration
records = records.toArray();
length = records.length;
for (i = 0; i < length; i++) {
record = records[i];
this.removeCanonicalRecord(record);
this.addCanonicalRecord(record, i);
}
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.fetchLink = function() {
var self = this;
return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function(records) {
self.updateRecordsFromAdapter(records);
return self.manyArray;
});
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.findRecords = function() {
var manyArray = this.manyArray;
return this.store.findMany(manyArray.toArray()).then(function() {
//Goes away after the manyArray refactor
manyArray.set('isLoaded', true);
return manyArray;
});
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.notifyHasManyChanged = function() {
this.record.notifyHasManyAdded(this.key);
};
ember$data$lib$system$relationships$state$has_many$$ManyRelationship.prototype.getRecords = function() {
//TODO(Igor) sync server here, once our syncing is not stupid
if (this.isAsync) {
var self = this;
var promise;
if (this.link) {
promise = this.findLink().then(function() {
return self.findRecords();
});
} else {
promise = this.findRecords();
}
return ember$data$lib$system$promise_proxies$$PromiseManyArray.create({
content: this.manyArray,
promise: promise
});
} else {
Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false));
//TODO(Igor) WTF DO I DO HERE?
if (!this.manyArray.get('isDestroyed')) {
this.manyArray.set('isLoaded', true);
}
return this.manyArray;
}
};
function ember$data$lib$system$relationships$state$has_many$$setForArray(array) {
var set = new ember$data$lib$system$map$$OrderedSet();
if (array) {
for (var i=0, l=array.length; i<l; i++) {
set.add(array[i]);
}
}
return set;
}
var ember$data$lib$system$relationships$state$has_many$$default = ember$data$lib$system$relationships$state$has_many$$ManyRelationship;
var ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship = function(store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.record = record;
this.key = relationshipMeta.key;
this.inverseRecord = null;
this.canonicalState = null;
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.constructor = ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.setRecord = function(newRecord) {
if (newRecord) {
this.addRecord(newRecord);
} else if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.setCanonicalRecord = function(newRecord) {
if (newRecord) {
this.addCanonicalRecord(newRecord);
} else if (this.inverseRecord) {
this.removeCanonicalRecord(this.inverseRecord);
}
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.addCanonicalRecord = function(newRecord) {
if (this.canonicalMembers.has(newRecord)) { return;}
if (this.canonicalState) {
this.removeCanonicalRecord(this.canonicalState);
}
this.canonicalState = newRecord;
this._super$addCanonicalRecord(newRecord);
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.flushCanonical = function() {
//temporary fix to not remove newly created records if server returned null.
//TODO remove once we have proper diffing
if (this.inverseRecord && this.inverseRecord.get('isNew') && !this.canonicalState) {
return;
}
this.inverseRecord = this.canonicalState;
this.record.notifyBelongsToChanged(this.key);
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.addRecord = function(newRecord) {
if (this.members.has(newRecord)) { return;}
var type = this.relationshipMeta.type;
Ember.assert("You can only add a '" + type.typeKey + "' record to this relationship", (function () {
if (newRecord instanceof type) {
return true;
} else if (Ember.MODEL_FACTORY_INJECTIONS) {
return newRecord instanceof type.superclass;
}
return false;
})());
if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
this.inverseRecord = newRecord;
this._super$addRecord(newRecord);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.setRecordPromise = function(newPromise) {
var content = newPromise.get && newPromise.get('content');
Ember.assert("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined);
this.setRecord(content);
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.removeRecordFromOwn = function(record) {
if (!this.members.has(record)) { return;}
this.inverseRecord = null;
this._super$removeRecordFromOwn(record);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function(record) {
if (!this.canonicalMembers.has(record)) { return;}
this.canonicalState = null;
this._super$removeCanonicalRecordFromOwn(record);
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.findRecord = function() {
if (this.inverseRecord) {
return this.store._findByRecord(this.inverseRecord);
} else {
return Ember.RSVP.Promise.resolve(null);
}
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.fetchLink = function() {
var self = this;
return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function(record) {
if (record) {
self.addRecord(record);
}
return record;
});
};
ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship.prototype.getRecord = function() {
//TODO(Igor) flushCanonical here once our syncing is not stupid
if (this.isAsync) {
var promise;
if (this.link) {
var self = this;
promise = this.findLink().then(function() {
return self.findRecord();
});
} else {
promise = this.findRecord();
}
return ember$data$lib$system$promise_proxies$$PromiseObject.create({
promise: promise,
content: this.inverseRecord
});
} else {
Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", this.inverseRecord === null || !this.inverseRecord.get('isEmpty'));
return this.inverseRecord;
}
};
var ember$data$lib$system$relationships$state$belongs_to$$default = ember$data$lib$system$relationships$state$belongs_to$$BelongsToRelationship;
var ember$data$lib$system$relationships$state$create$$createRelationshipFor = function(record, relationshipMeta, store) {
var inverseKey;
var inverse = record.constructor.inverseFor(relationshipMeta.key);
if (inverse) {
inverseKey = inverse.name;
}
if (relationshipMeta.kind === 'hasMany') {
return new ember$data$lib$system$relationships$state$has_many$$default(store, record, inverseKey, relationshipMeta);
} else {
return new ember$data$lib$system$relationships$state$belongs_to$$default(store, record, inverseKey, relationshipMeta);
}
};
var ember$data$lib$system$relationships$state$create$$default = ember$data$lib$system$relationships$state$create$$createRelationshipFor;
/**
@module ember-data
*/
var ember$data$lib$system$snapshot$$get = Ember.get;
/**
@class Snapshot
@namespace DS
@private
@constructor
@param {DS.Model} record The record to create a snapshot from
*/
function ember$data$lib$system$snapshot$$Snapshot(record) {
this._attributes = Ember.create(null);
this._belongsToRelationships = Ember.create(null);
this._belongsToIds = Ember.create(null);
this._hasManyRelationships = Ember.create(null);
this._hasManyIds = Ember.create(null);
record.eachAttribute(function(keyName) {
this._attributes[keyName] = ember$data$lib$system$snapshot$$get(record, keyName);
}, this);
this.id = ember$data$lib$system$snapshot$$get(record, 'id');
this.record = record;
this.type = record.constructor;
this.typeKey = record.constructor.typeKey;
// The following code is here to keep backwards compatibility when accessing
// `constructor` directly.
//
// With snapshots you should use `type` instead of `constructor`.
//
// Remove for Ember Data 1.0.
if (Ember.platform.hasPropertyAccessors) {
var callDeprecate = true;
Ember.defineProperty(this, 'constructor', {
get: function() {
// Ugly hack since accessing error.stack (done in `Ember.deprecate()`)
// causes the internals of Chrome to access the constructor, which then
// causes an infinite loop if accessed and calls `Ember.deprecate()`
// again.
if (callDeprecate) {
callDeprecate = false;
Ember.deprecate('Usage of `snapshot.constructor` is deprecated, use `snapshot.type` instead.');
callDeprecate = true;
}
return this.type;
}
});
} else {
this.constructor = this.type;
}
}
ember$data$lib$system$snapshot$$Snapshot.prototype = {
constructor: ember$data$lib$system$snapshot$$Snapshot,
/**
The id of the snapshot's underlying record
Example
```javascript
var post = store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
var snapshot = post._createSnapshot();
snapshot.id; // => '1'
```
@property id
@type {String}
*/
id: null,
/**
The underlying record for this snapshot. Can be used to access methods and
properties defined on the record.
Example
```javascript
var json = snapshot.record.toJSON();
```
@property record
@type {DS.Model}
*/
record: null,
/**
The type of the underlying record for this snapshot, as a subclass of DS.Model.
@property type
@type {subclass of DS.Model}
*/
type: null,
/**
The name of the type of the underlying record for this snapshot, as a string.
@property typeKey
@type {String}
*/
typeKey: null,
/**
Returns the value of an attribute.
Example
```javascript
var post = store.createRecord('post', { author: 'Tomster', title: 'Ember.js rocks' });
var snapshot = post._createSnapshot();
snapshot.attr('author'); // => 'Tomster'
snapshot.attr('title'); // => 'Ember.js rocks'
```
Note: Values are loaded eagerly and cached when the snapshot is created.
@method attr
@param {String} keyName
@return {Object} The attribute value or undefined
*/
attr: function(keyName) {
if (keyName in this._attributes) {
return this._attributes[keyName];
}
throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no attribute named '" + keyName + "' defined.");
},
/**
Returns all attributes and their corresponding values.
Example
```javascript
var post = store.createRecord('post', { author: 'Tomster', title: 'Ember.js rocks' });
var snapshot = post._createSnapshot();
snapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' }
```
@method attributes
@return {Array} All attributes for the current snapshot
*/
attributes: function() {
return Ember.copy(this._attributes);
},
/**
Returns the current value of a belongsTo relationship.
`belongsTo` takes an optional hash of options as a second parameter,
currently supported options are:
- `id`: set to `true` if you only want the ID of the related record to be
returned.
Example
```javascript
var post = store.push('post', { id: 1, title: 'Hello World' });
var comment = store.createRecord('comment', { body: 'Lorem ipsum', post: post });
var snapshot = comment._createSnapshot();
snapshot.belongsTo('post'); // => DS.Snapshot of post
snapshot.belongsTo('post', { id: true }); // => '1'
```
Calling `belongsTo` will return a new Snapshot as long as there's any
data available, such as an ID. If there's no data available `belongsTo` will
return undefined.
Note: Relationships are loaded lazily and cached upon first access.
@method belongsTo
@param {String} keyName
@param {Object} [options]
@return {DS.Snapshot|String|undefined} A snapshot or ID of a belongsTo relationship, or undefined
*/
belongsTo: function(keyName, options) {
var id = options && options.id;
var result;
var relationship, inverseRecord;
if (id && keyName in this._belongsToIds) {
return this._belongsToIds[keyName];
}
if (!id && keyName in this._belongsToRelationships) {
return this._belongsToRelationships[keyName];
}
relationship = this.record._relationships[keyName];
if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) {
throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined.");
}
inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord');
if (id) {
if (inverseRecord) {
result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id');
}
this._belongsToIds[keyName] = result;
} else {
if (inverseRecord) {
result = inverseRecord._createSnapshot();
}
this._belongsToRelationships[keyName] = result;
}
return result;
},
/**
Returns the current value of a hasMany relationship.
`hasMany` takes an optional hash of options as a second parameter,
currently supported options are:
- `ids`: set to `true` if you only want the IDs of the related records to be
returned.
Example
```javascript
var post = store.createRecord('post', { title: 'Hello World', comments: [2, 3] });
var snapshot = post._createSnapshot();
snapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot]
snapshot.hasMany('comments', { ids: true }); // => ['2', '3']
```
Note: Relationships are loaded lazily and cached upon first access.
@method hasMany
@param {String} keyName
@param {Object} [options]
@return {Array} An array of snapshots or IDs of a hasMany relationship
*/
hasMany: function(keyName, options) {
var ids = options && options.ids;
var results = [];
var relationship, members;
if (ids && keyName in this._hasManyIds) {
return this._hasManyIds[keyName];
}
if (!ids && keyName in this._hasManyRelationships) {
return this._hasManyRelationships[keyName];
}
relationship = this.record._relationships[keyName];
if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) {
throw new Ember.Error("Model '" + Ember.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined.");
}
members = ember$data$lib$system$snapshot$$get(relationship, 'members');
if (ids) {
members.forEach(function(member) {
results.push(ember$data$lib$system$snapshot$$get(member, 'id'));
});
this._hasManyIds[keyName] = results;
} else {
members.forEach(function(member) {
results.push(member._createSnapshot());
});
this._hasManyRelationships[keyName] = results;
}
return results;
},
/**
Iterates through all the attributes of the model, calling the passed
function on each attribute.
Example
```javascript
snapshot.eachAttribute(function(name, meta) {
// ...
});
```
@method eachAttribute
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachAttribute: function(callback, binding) {
this.record.eachAttribute(callback, binding);
},
/**
Iterates through all the relationships of the model, calling the passed
function on each relationship.
Example
```javascript
snapshot.eachRelationship(function(name, relationship) {
// ...
});
```
@method eachRelationship
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.record.eachRelationship(callback, binding);
},
/**
@method get
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
get: function(keyName) {
Ember.deprecate('Using DS.Snapshot.get() is deprecated. Use .attr(), .belongsTo() or .hasMany() instead.');
if (keyName === 'id') {
return this.id;
}
if (keyName in this._attributes) {
return this.attr(keyName);
}
var relationship = this.record._relationships[keyName];
if (relationship && relationship.relationshipMeta.kind === 'belongsTo') {
return this.belongsTo(keyName);
}
if (relationship && relationship.relationshipMeta.kind === 'hasMany') {
return this.hasMany(keyName);
}
return ember$data$lib$system$snapshot$$get(this.record, keyName);
},
/**
@method unknownProperty
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
unknownProperty: function(keyName) {
return this.get(keyName);
}
};
var ember$data$lib$system$snapshot$$default = ember$data$lib$system$snapshot$$Snapshot;
/**
@module ember-data
*/
var ember$data$lib$system$model$model$$get = Ember.get;
var ember$data$lib$system$model$model$$set = Ember.set;
var ember$data$lib$system$model$model$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$model$model$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$system$model$model$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed('currentState', function(key, value) {
return ember$data$lib$system$model$model$$get(ember$data$lib$system$model$model$$get(this, 'currentState'), key);
}).readOnly();
var ember$data$lib$system$model$model$$_extractPivotNameCache = Ember.create(null);
var ember$data$lib$system$model$model$$_splitOnDotCache = Ember.create(null);
function ember$data$lib$system$model$model$$splitOnDot(name) {
return ember$data$lib$system$model$model$$_splitOnDotCache[name] || (
(ember$data$lib$system$model$model$$_splitOnDotCache[name] = name.split('.'))
);
}
function ember$data$lib$system$model$model$$extractPivotName(name) {
return ember$data$lib$system$model$model$$_extractPivotNameCache[name] || (
(ember$data$lib$system$model$model$$_extractPivotNameCache[name] = ember$data$lib$system$model$model$$splitOnDot(name)[0])
);
}
// Like Ember.merge, but instead returns a list of keys
// for values that fail a strict equality check
// instead of the original object.
function ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(original, updates) {
var changedKeys = [];
if (!updates || typeof updates !== 'object') {
return changedKeys;
}
var keys = Ember.keys(updates);
var length = keys.length;
var i, val, key;
for (i = 0; i < length; i++) {
key = keys[i];
val = updates[key];
if (original[key] !== val) {
changedKeys.push(key);
}
original[key] = val;
}
return changedKeys;
}
/**
The model class that all Ember Data records descend from.
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var ember$data$lib$system$model$model$$Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.get('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('isDirty'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
The `clientId` property is a transient numerical identifier
generated at runtime by the data store. It is important
primarily because newly created objects may not yet have an
externally generated id.
@property clientId
@private
@type {Number|String}
*/
clientId: null,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: ember$data$lib$system$model$states$$default.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
typically contains keys corresponding to the invalid property names
and values which are an array of error messages.
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('errors').get('foo'); // ['foo should be a number.']
});
```
@property errors
@type {DS.Errors}
*/
errors: Ember.computed(function() {
var errors = ember$data$lib$system$model$errors$$default.create();
errors.registerHandlers(this, function() {
this.send('becameInvalid');
}, function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = ember$data$lib$system$model$model$$get(this, 'store');
return store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON: function(options) {
// container is for lazy transform lookups
var serializer = ember$data$lib$serializers$json_serializer$$default.create({ container: this.container });
var snapshot = this._createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: function() {
this.store.recordArrayManager.recordWasLoaded(this);
},
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when the record is created.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed(function() {
this._data = this._data || {};
return this._data;
}).readOnly(),
_data: null,
init: function() {
this._super.apply(this, arguments);
this._setup();
},
_setup: function() {
this._changesToSync = {};
this._deferredTriggers = [];
this._data = {};
this._attributes = Ember.create(null);
this._inFlightAttributes = Ember.create(null);
this._relationships = {};
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```
App.Comment = DS.Model.extend({
name: DS.attr()
})
```
but there is also
```
App.Post = DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
this._implicitRelationships = Ember.create(null);
var model = this;
//TODO Move into a getter for better perf
this.constructor.eachRelationship(function(key, descriptor) {
model._relationships[key] = ember$data$lib$system$relationships$state$create$$default(model, descriptor, model.store);
});
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = ember$data$lib$system$model$model$$get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct references to state objects
var pivotName = ember$data$lib$system$model$model$$extractPivotName(name);
var currentState = ember$data$lib$system$model$model$$get(this, 'currentState');
var state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = ember$data$lib$system$model$model$$splitOnDot(name);
var setups = [];
var enters = [];
var i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
ember$data$lib$system$model$model$$set(this, 'currentState', state);
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
withTransaction: function(fn) {
var transaction = ember$data$lib$system$model$model$$get(this, 'transaction');
if (transaction) { fn(transaction); }
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this.send('deleteRecord');
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function() {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
if (this.isDestroyed) { return; }
this.send('unloadRecord');
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
var rel = this._relationships[name];
if (rel) {
//TODO(Igor) figure out whether we want to clear or disconnect
rel.clear();
rel.destroy();
}
}, this);
},
disconnectRelationships: function() {
this.eachRelationship(function(name, relationship) {
this._relationships[name].disconnect();
}, this);
var model = this;
ember$data$lib$system$model$model$$forEach.call(Ember.keys(this._implicitRelationships), function(key) {
model._implicitRelationships[key].disconnect();
});
},
reconnectRelationships: function() {
this.eachRelationship(function(name, relationship) {
this._relationships[name].reconnect();
}, this);
var model = this;
ember$data$lib$system$model$model$$forEach.call(Ember.keys(this._implicitRelationships), function(key) {
model._implicitRelationships[key].reconnect();
});
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
this._updatingRecordArraysLater = false;
ember$data$lib$system$model$model$$get(this, 'store').dataWasUpdated(this.constructor, this);
},
/**
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.find('comment', 2, {post:1})` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method _preloadData
@private
@param {Object} preload
*/
_preloadData: function(preload) {
var record = this;
//TODO(Igor) consider the polymorphic case
ember$data$lib$system$model$model$$forEach.call(Ember.keys(preload), function(key) {
var preloadValue = ember$data$lib$system$model$model$$get(preload, key);
var relationshipMeta = record.constructor.metaForProperty(key);
if (relationshipMeta.isRelationship) {
record._preloadRelationship(key, preloadValue);
} else {
ember$data$lib$system$model$model$$get(record, '_data')[key] = preloadValue;
}
});
},
_preloadRelationship: function(key, preloadValue) {
var relationshipMeta = this.constructor.metaForProperty(key);
var type = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany') {
this._preloadHasMany(key, preloadValue, type);
} else {
this._preloadBelongsTo(key, preloadValue, type);
}
},
_preloadHasMany: function(key, preloadValue, type) {
Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue));
var record = this;
var recordsToSet = ember$data$lib$system$model$model$$map.call(preloadValue, function(recordToPush) {
return record._convertStringOrNumberIntoRecord(recordToPush, type);
});
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships[key].updateRecordsFromAdapter(recordsToSet);
},
_preloadBelongsTo: function(key, preloadValue, type) {
var recordToSet = this._convertStringOrNumberIntoRecord(preloadValue, type);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships[key].setRecord(recordToSet);
},
_convertStringOrNumberIntoRecord: function(value, type) {
if (Ember.typeOf(value) === 'string' || Ember.typeOf(value) === 'number') {
return this.store.recordForId(type, value);
}
return value;
},
/**
@method _notifyProperties
@private
*/
_notifyProperties: function(keys) {
Ember.beginPropertyChanges();
var key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```javascript
App.Mascot = DS.Model.extend({
name: attr('string')
});
var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = ember$data$lib$system$model$model$$get(this, '_data');
var newData = ember$data$lib$system$model$model$$get(this, '_attributes');
var diffData = {};
var prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
var changedKeys;
ember$data$lib$system$model$model$$set(this, 'isError', false);
if (data) {
changedKeys = ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(this._data, data);
} else {
ember$data$lib$system$merge$$default(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = Ember.create(null);
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this._notifyProperties(changedKeys);
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) { return; }
this._updatingRecordArraysLater = true;
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
/**
@method setupData
@private
@param {Object} data
*/
setupData: function(data) {
Ember.assert("Expected an object as `data` in `setupData`", Ember.typeOf(data) === 'object');
var changedKeys = ember$data$lib$system$model$model$$mergeAndReturnChangedKeys(this._data, data);
this.pushedData();
this._notifyProperties(changedKeys);
},
materializeId: function(id) {
ember$data$lib$system$model$model$$set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass an object to materializeAttributes", !!attributes);
ember$data$lib$system$merge$$default(this._data, attributes);
},
materializeAttribute: function(name, value) {
this._data[name] = value;
},
/**
If the model `isDirty` this function will discard any unsaved
changes
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function() {
var dirtyKeys = Ember.keys(this._attributes);
this._attributes = Ember.create(null);
if (ember$data$lib$system$model$model$$get(this, 'isError')) {
this._inFlightAttributes = Ember.create(null);
ember$data$lib$system$model$model$$set(this, 'isError', false);
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (ember$data$lib$system$model$model$$get(this, 'isDeleted')) {
this.reconnectRelationships();
}
if (ember$data$lib$system$model$model$$get(this, 'isNew')) {
this.clearRelationships();
}
if (!ember$data$lib$system$model$model$$get(this, 'isValid')) {
this._inFlightAttributes = Ember.create(null);
}
this.send('rolledBack');
this._notifyProperties(dirtyKeys);
},
/**
@method _createSnapshot
@private
*/
_createSnapshot: function() {
return new ember$data$lib$system$snapshot$$default(this);
},
toStringExtension: function() {
return ember$data$lib$system$model$model$$get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function() {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.get('store').scheduleSave(this, resolver);
this._inFlightAttributes = this._attributes;
this._attributes = Ember.create(null);
return ember$data$lib$system$promise_proxies$$PromiseObject.create({
promise: resolver.promise
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```javascript
App.ModelViewRoute = Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
ember$data$lib$system$model$model$$set(this, 'isReloading', true);
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
var promise = new ember$data$lib$system$model$model$$Promise(function(resolve) {
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.set('isReloading', false);
record.set('isError', false);
return record;
}, function(reason) {
record.set('isError', true);
throw reason;
}, "DS: Model#reload complete, update flags")['finally'](function () {
record.updateRecordArrays();
});
return ember$data$lib$system$promise_proxies$$PromiseObject.create({
promise: promise
});
},
// FOR USE DURING COMMIT PROCESS
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
var recordErrors = ember$data$lib$system$model$model$$get(this, 'errors');
for (var key in errors) {
if (!errors.hasOwnProperty(key)) {
continue;
}
recordErrors.add(key, errors[key]);
}
this._saveWasRejected();
},
/**
@method adapterDidError
@private
*/
adapterDidError: function() {
this.send('becameError');
ember$data$lib$system$model$model$$set(this, 'isError', true);
this._saveWasRejected();
},
_saveWasRejected: function() {
var keys = Ember.keys(this._inFlightAttributes);
for (var i=0; i < keys.length; i++) {
if (this._attributes[keys[i]] === undefined) {
this._attributes[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
this._inFlightAttributes = Ember.create(null);
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger: function() {
var length = arguments.length;
var args = new Array(length - 1);
var name = arguments[0];
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
Ember.tryInvoke(this, name, args);
this._super.apply(this, arguments);
},
triggerLater: function() {
var length = arguments.length;
var args = new Array(length);
for (var i = 0; i < length; i++) {
args[i] = arguments[i];
}
if (this._deferredTriggers.push(args) !== 1) {
return;
}
Ember.run.schedule('actions', this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
for (var i=0, l= this._deferredTriggers.length; i<l; i++) {
this.trigger.apply(this, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
willDestroy: function() {
this._super.apply(this, arguments);
this.clearRelationships();
},
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin: function(props) {
Ember.assert('`data` is a reserved property name on DS.Model objects. Please choose a different property name for ' + this.constructor.toString(), !props.data);
}
});
ember$data$lib$system$model$model$$Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: ember$data$lib$system$model$model$$Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
}
});
var ember$data$lib$system$model$model$$default = ember$data$lib$system$model$model$$Model;
/**
@module ember-data
*/
var ember$data$lib$system$model$attributes$$get = Ember.get;
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$model$$default.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
var attributes = Ember.get(App.Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isAttribute) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
var map = ember$data$lib$system$map$$Map.create();
this.eachAttribute(function(key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachAttribute: function(callback, binding) {
ember$data$lib$system$model$attributes$$get(this, 'attributes').forEach(function(meta, name) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachTransformedAttribute: function(callback, binding) {
ember$data$lib$system$model$attributes$$get(this, 'transformedAttributes').forEach(function(type, name) {
callback.call(binding, name, type);
});
}
});
ember$data$lib$system$model$model$$default.reopen({
eachAttribute: function(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function ember$data$lib$system$model$attributes$$getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function ember$data$lib$system$model$attributes$$hasValue(record, key) {
return key in record._attributes ||
key in record._inFlightAttributes ||
record._data.hasOwnProperty(key);
}
function ember$data$lib$system$model$attributes$$getValue(record, key) {
if (key in record._attributes) {
return record._attributes[key];
} else if (key in record._inFlightAttributes) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
function ember$data$lib$system$model$attributes$$attr(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
options = options || {};
}
var meta = {
type: type,
isAttribute: true,
options: options
};
return Ember.computed(function(key, value) {
if (arguments.length > 1) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
var oldValue = ember$data$lib$system$model$attributes$$getValue(this, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
this._attributes[key] = value;
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: this._data[key],
value: value
});
}
return value;
} else if (ember$data$lib$system$model$attributes$$hasValue(this, key)) {
return ember$data$lib$system$model$attributes$$getValue(this, key);
} else {
return ember$data$lib$system$model$attributes$$getDefaultValue(this, options, key);
}
// `data` is never set directly. However, it may be
// invalidated from the state manager's setData
// event.
}).meta(meta);
}
var ember$data$lib$system$model$attributes$$default = ember$data$lib$system$model$attributes$$attr;
//Stanley told me to do this
var ember$data$lib$system$store$$Backburner = Ember.__loader.require('backburner')['default'] || Ember.__loader.require('backburner')['Backburner'];
//Shim Backburner.join
if (!ember$data$lib$system$store$$Backburner.prototype.join) {
var ember$data$lib$system$store$$isString = function(suspect) {
return typeof suspect === 'string';
};
ember$data$lib$system$store$$Backburner.prototype.join = function(/*target, method, args */) {
var method, target;
if (this.currentInstance) {
var length = arguments.length;
if (length === 1) {
method = arguments[0];
target = null;
} else {
target = arguments[0];
method = arguments[1];
}
if (ember$data$lib$system$store$$isString(method)) {
method = target[method];
}
if (length === 1) {
return method();
} else if (length === 2) {
return method.call(target);
} else {
var args = new Array(length - 2);
for (var i =0, l = length - 2; i < l; i++) {
args[i] = arguments[i + 2];
}
return method.apply(target, args);
}
} else {
return this.run.apply(this, arguments);
}
};
}
var ember$data$lib$system$store$$get = Ember.get;
var ember$data$lib$system$store$$set = Ember.set;
var ember$data$lib$system$store$$once = Ember.run.once;
var ember$data$lib$system$store$$isNone = Ember.isNone;
var ember$data$lib$system$store$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$store$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$store$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$store$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$store$$copy = Ember.copy;
var ember$data$lib$system$store$$Store;
var ember$data$lib$system$store$$camelize = Ember.String.camelize;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +reference+ means a record reference object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a subclass of DS.Model.
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function ember$data$lib$system$store$$coerceId(id) {
return id == null ? null : id+'';
}
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```javascript
MyApp.ApplicationStore = DS.Store.extend();
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
store.find('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```javascript
MyApp.ApplicationAdapter = MyApp.CustomAdapter
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#all()`, `store#findAll()` or `store#filter()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Object
*/
ember$data$lib$system$store$$Store = Ember.Object.extend({
/**
@method init
@private
*/
init: function() {
this._backburner = new ember$data$lib$system$store$$Backburner(['normalizeRelationships', 'syncRelationships', 'finished']);
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = ember$data$lib$system$record_array_manager$$default.create({
store: this
});
this._pendingSave = [];
//Used to keep track of all the find requests that need to be coalesced
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `App.CustomAdapter` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {DS.Adapter|String}
*/
adapter: '-rest',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function(record, options) {
var snapshot = record._createSnapshot();
return this.serializerFor(snapshot.typeKey).serialize(snapshot, options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: Ember.computed('adapter', function() {
var adapter = ember$data$lib$system$store$$get(this, 'adapter');
Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof ember$data$lib$system$adapter$$Adapter));
if (typeof adapter === 'string') {
adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest');
}
if (DS.Adapter.detect(adapter)) {
adapter = adapter.create({
container: this.container
});
}
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} type
@param {Object} properties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord: function(typeName, inputProperties) {
var type = this.modelFor(typeName);
var properties = ember$data$lib$system$store$$copy(inputProperties) || {};
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (ember$data$lib$system$store$$isNone(properties.id)) {
properties.id = this._generateId(type, properties);
}
// Coerce ID to a string
properties.id = ember$data$lib$system$store$$coerceId(properties.id);
var record = this.buildRecord(type, properties.id);
// Move the record out of its initial `empty` state into
// the `loaded` state.
record.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} type
@param {Object} properties from the new record
@return {String} if the adapter can generate one, an ID
*/
_generateId: function(type, properties) {
var adapter = this.adapterFor(type);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this, type, properties);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
You can optionally `preload` specific attributes and relationships that you know of
by passing them as the third argument to find.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `find` call:
```javascript
store.find('comment', 2, {post: 1});
```
If you have access to the post model you can also pass the model itself:
```javascript
store.find('post', 1).then(function (myPostModel) {
store.find('comment', 2, {post: myPostModel});
});
```
This way, your adapter's `find` or `buildURL` method will be able to look up the
relationship on the record and construct the nested URL without having to first
fetch the post.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values. The promise will resolve into all records of this type
present in the store, even if the server only returns a subset of them.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find('person', { page: 1 });
```
By passing an object `{page: 1}` as an argument to the find method, it
delegates to the adapter's findQuery method. The adapter then makes
a call to the server, transforming the object `{page: 1}` as parameters
that are sent along, and will return a RecordArray when the promise
resolves.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
The call made to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?page=1"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"page"=>"1"}
```
If you do something like this:
```javascript
store.find('person', {ids: [1, 2, 3]});
```
The call to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"ids"=>["1", "2", "3"]}
```
@method find
@param {String or subclass of DS.Model} type
@param {Object|String|Integer|null} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
find: function(type, id, preload) {
Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1);
Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id));
if (arguments.length === 1) {
return this.findAll(type);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === 'object') {
return this.findQuery(type, id);
}
return this.findById(type, ember$data$lib$system$store$$coerceId(id), preload);
},
/**
This method returns a fresh record for a given type and id combination.
If a record is available for the given type/id combination, then
it will fetch this record from the store and call `reload()` on it.
That will fire a request to server and return a promise that will
resolve once the record has been reloaded.
If there's no record corresponding in the store it will simply call
`store.find`.
Example
```javascript
App.PostRoute = Ember.Route.extend({
model: function(params) {
return this.store.fetch('post', params.post_id);
}
});
```
@method fetchById
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
fetchById: function(type, id, preload) {
if (this.hasRecordForId(type, id)) {
return this.getById(type, id).reload();
} else {
return this.find(type, id, preload);
}
},
/**
This method returns a fresh collection from the server, regardless of if there is already records
in the store or not.
@method fetchAll
@param {String or subclass of DS.Model} type
@return {Promise} promise
*/
fetchAll: function(type) {
type = this.modelFor(type);
return this._fetchAll(type, this.all(type));
},
/**
@method fetch
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
@deprecated Use [fetchById](#method_fetchById) instead
*/
fetch: function(type, id, preload) {
Ember.deprecate('Using store.fetch() has been deprecated. Use store.fetchById for fetching individual records or store.fetchAll for collections');
return this.fetchById(type, id, preload);
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
findById: function(typeName, id, preload) {
var type = this.modelFor(typeName);
var record = this.recordForId(type, id);
return this._findByRecord(record, preload);
},
_findByRecord: function(record, preload) {
var fetchedRecord;
if (preload) {
record._preloadData(preload);
}
if (ember$data$lib$system$store$$get(record, 'isEmpty')) {
fetchedRecord = this.scheduleFetch(record);
//TODO double check about reloading
} else if (ember$data$lib$system$store$$get(record, 'isLoading')) {
fetchedRecord = record._loadingPromise;
}
return ember$data$lib$system$promise_proxies$$promiseObject(fetchedRecord || record, "DS: Store#findByRecord " + record.typeKey + " with id: " + ember$data$lib$system$store$$get(record, 'id'));
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} type
@param {Array} ids
@return {Promise} promise
*/
findByIds: function(type, ids) {
var store = this;
return ember$data$lib$system$promise_proxies$$promiseArray(Ember.RSVP.all(ember$data$lib$system$store$$map(ids, function(id) {
return store.findById(type, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
fetchRecord: function(record) {
var type = record.constructor;
var id = ember$data$lib$system$store$$get(record, 'id');
var adapter = this.adapterFor(type);
Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", typeof adapter.find === 'function');
var promise = ember$data$lib$system$store$$_find(adapter, this, type, id, record);
return promise;
},
scheduleFetchMany: function(records) {
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(records, this.scheduleFetch, this));
},
scheduleFetch: function(record) {
var type = record.constructor;
if (ember$data$lib$system$store$$isNone(record)) { return null; }
if (record._loadingPromise) { return record._loadingPromise; }
var resolver = Ember.RSVP.defer('Fetching ' + type + 'with id: ' + record.get('id'));
var recordResolverPair = {
record: record,
resolver: resolver
};
var promise = resolver.promise;
record.loadingData(promise);
if (!this._pendingFetch.get(type)) {
this._pendingFetch.set(type, [recordResolverPair]);
} else {
this._pendingFetch.get(type).push(recordResolverPair);
}
Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches);
return promise;
},
flushAllPendingFetches: function() {
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
_flushPendingFetchForType: function (recordResolverPairs, type) {
var store = this;
var adapter = store.adapterFor(type);
var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
var records = Ember.A(recordResolverPairs).mapBy('record');
function _fetchRecord(recordResolverPair) {
recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record));
}
function resolveFoundRecords(records) {
ember$data$lib$system$store$$forEach(records, function(record) {
var pair = Ember.A(recordResolverPairs).findBy('record', record);
if (pair) {
var resolver = pair.resolver;
resolver.resolve(record);
}
});
}
function makeMissingRecordsRejector(requestedRecords) {
return function rejectMissingRecords(resolvedRecords) {
var missingRecords = requestedRecords.without(resolvedRecords);
rejectRecords(missingRecords);
};
}
function makeRecordsRejector(records) {
return function (error) {
rejectRecords(records, error);
};
}
function rejectRecords(records, error) {
ember$data$lib$system$store$$forEach(records, function(record) {
var pair = Ember.A(recordResolverPairs).findBy('record', record);
if (pair) {
var resolver = pair.resolver;
resolver.reject(error);
}
});
}
if (recordResolverPairs.length === 1) {
_fetchRecord(recordResolverPairs[0]);
} else if (shouldCoalesce) {
var groups = adapter.groupRecordsForFindMany(this, records);
ember$data$lib$system$store$$forEach(groups, function (groupOfRecords) {
var requestedRecords = Ember.A(groupOfRecords);
var ids = requestedRecords.mapBy('id');
if (ids.length > 1) {
ember$data$lib$system$store$$_findMany(adapter, store, type, ids, requestedRecords).
then(resolveFoundRecords).
then(makeMissingRecordsRejector(requestedRecords)).
then(null, makeRecordsRejector(requestedRecords));
} else if (ids.length === 1) {
var pair = Ember.A(recordResolverPairs).findBy('record', groupOfRecords[0]);
_fetchRecord(pair);
} else {
Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false);
}
});
} else {
ember$data$lib$system$store$$forEach(recordResolverPairs, _fetchRecord);
}
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
_Note: This is an synchronous method and does not return a promise._
```js
var post = store.getById('post', 1);
post.get('id'); // 1
```
@method getById
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {DS.Model|null} record
*/
getById: function(type, id) {
if (this.hasRecordForId(type, id)) {
return this.recordForId(type, id);
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
reloadRecord: function(record) {
var type = record.constructor;
var adapter = this.adapterFor(type);
var id = ember$data$lib$system$store$$get(record, 'id');
Ember.assert("You cannot reload a record without an ID", id);
Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to reload a record but your adapter does not implement `find`", typeof adapter.find === 'function');
return this.scheduleFetch(record);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {Boolean}
*/
hasRecordForId: function(typeName, inputId) {
var type = this.modelFor(typeName);
var id = ember$data$lib$system$store$$coerceId(inputId);
return !!this.typeMapFor(type).idToRecord[id];
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {DS.Model} record
*/
recordForId: function(typeName, inputId) {
var type = this.modelFor(typeName);
var id = ember$data$lib$system$store$$coerceId(inputId);
var idToRecord = this.typeMapFor(type).idToRecord;
var record = idToRecord[id];
if (!record || !idToRecord[id]) {
record = this.buildRecord(type, id);
}
return record;
},
/**
@method findMany
@private
@param {DS.Model} owner
@param {Array} records
@param {String or subclass of DS.Model} type
@param {Resolver} resolver
@return {DS.ManyArray} records
*/
findMany: function(records) {
var store = this;
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(records, function(record) {
return store._findByRecord(record);
}));
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {String or subclass of DS.Model} type
@return {Promise} promise
*/
findHasMany: function(owner, link, type) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function');
return ember$data$lib$system$store$$_findHasMany(adapter, this, owner, link, type);
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function(owner, link, relationship) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function');
return ember$data$lib$system$store$$_findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String or subclass of DS.Model} type
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function(typeName, query) {
var type = this.modelFor(typeName);
var array = this.recordArrayManager
.createAdapterPopulatedRecordArray(type, query);
var adapter = this.adapterFor(type);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", typeof adapter.findQuery === 'function');
return ember$data$lib$system$promise_proxies$$promiseArray(ember$data$lib$system$store$$_findQuery(adapter, this, type, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String or subclass of DS.Model} type
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function(typeName) {
return this.fetchAll(typeName);
},
/**
@method _fetchAll
@private
@param {DS.Model} type
@param {DS.RecordArray} array
@return {Promise} promise
*/
_fetchAll: function(type, array) {
var adapter = this.adapterFor(type);
var sinceToken = this.typeMapFor(type).metadata.since;
ember$data$lib$system$store$$set(array, 'isUpdating', true);
Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function');
return ember$data$lib$system$promise_proxies$$promiseArray(ember$data$lib$system$store$$_findAll(adapter, this, type, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} type
*/
didUpdateAll: function(type) {
var findAllCache = this.typeMapFor(type).findAllCache;
ember$data$lib$system$store$$set(findAllCache, 'isUpdating', false);
},
/**
This method returns a filtered array that contains all of the
known records for a given type in the store.
Note that because it's just a filter, the result will contain any
locally created records of the type, however, it will not make a
request to the backend to retrieve additional records. If you
would like to request all the records from the backend please use
[store.find](#method_find).
Also note that multiple calls to `all` for a given type will always
return the same `RecordArray`.
Example
```javascript
var localPosts = store.all('post');
```
@method all
@param {String or subclass of DS.Model} type
@return {DS.RecordArray}
*/
all: function(typeName) {
var type = this.modelFor(typeName);
var typeMap = this.typeMapFor(type);
var findAllCache = typeMap.findAllCache;
if (findAllCache) {
this.recordArrayManager.updateFilter(findAllCache, type);
return findAllCache;
}
var array = this.recordArrayManager.createRecordArray(type);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all of the known records for a given type.
```javascript
store.unloadAll('post');
```
@method unloadAll
@param {String or subclass of DS.Model} type
*/
unloadAll: function(type) {
var modelType = this.modelFor(type);
var typeMap = this.typeMapFor(modelType);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The filter function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
Example
```javascript
store.filter('post', function(post) {
return post.get('unread');
});
```
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query, which is the equivalent of calling
[find](#method_find) with that same query, to fetch additional records
from the server. The results returned by the server could then appear
in the filter if they match the filter function.
The query itself is not used to filter records, it's only sent to your
server for you to be able to do server-side filtering. The filter
function will be applied on the returned results regardless.
Example
```javascript
store.filter('post', { unread: true }, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String or subclass of DS.Model} type
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function(type, query, filter) {
var promise;
var length = arguments.length;
var array;
var hasQuery = length === 3;
// allow an optional server query
if (hasQuery) {
promise = this.findQuery(type, query);
} else if (arguments.length === 2) {
filter = query;
}
type = this.modelFor(type);
if (hasQuery) {
array = this.recordArrayManager.createFilteredRecordArray(type, filter, query);
} else {
array = this.recordArrayManager.createFilteredRecordArray(type, filter);
}
promise = promise || ember$data$lib$system$store$$Promise.cast(array);
return ember$data$lib$system$promise_proxies$$promiseArray(promise.then(function() {
return array;
}, null, "DS: Store#filter of " + type));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
store.recordIsLoaded('post', 1); // true
});
```
@method recordIsLoaded
@param {String or subclass of DS.Model} type
@param {string} id
@return {boolean}
*/
recordIsLoaded: function(type, id) {
if (!this.hasRecordForId(type, id)) { return false; }
return !ember$data$lib$system$store$$get(this.recordForId(type, id), 'isEmpty');
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String or subclass of DS.Model} typeName
@return {object}
*/
metadataFor: function(typeName) {
var type = this.modelFor(typeName);
return this.typeMapFor(type).metadata;
},
/**
This method sets the metadata for a specific type.
@method setMetadataFor
@param {String or subclass of DS.Model} typeName
@param {Object} metadata metadata to set
@return {object}
*/
setMetadataFor: function(typeName, metadata) {
var type = this.modelFor(typeName);
Ember.merge(this.typeMapFor(type).metadata, metadata);
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes the record will notify
the store to update its membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {DS.Model} record
*/
dataWasUpdated: function(type, record) {
this.recordArrayManager.recordDidChange(record);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
scheduleSave: function(record, resolver) {
record.adapterWillCommit();
this._pendingSave.push([record, resolver]);
ember$data$lib$system$store$$once(this, 'flushPendingSave');
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function() {
var pending = this._pendingSave.slice();
this._pendingSave = [];
ember$data$lib$system$store$$forEach(pending, function(tuple) {
var record = tuple[0];
var resolver = tuple[1];
var adapter = this.adapterFor(record.constructor);
var operation;
if (ember$data$lib$system$store$$get(record, 'currentState.stateName') === 'root.deleted.saved') {
return resolver.resolve(record);
} else if (ember$data$lib$system$store$$get(record, 'isNew')) {
operation = 'createRecord';
} else if (ember$data$lib$system$store$$get(record, 'isDeleted')) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(ember$data$lib$system$store$$_commit(adapter, this, operation, record));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {DS.Model} record the in-flight record
@param {Object} data optional data (see above)
*/
didSaveRecord: function(record, data) {
if (data) {
// normalize relationship IDs into records
this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', record, record.constructor, data);
this.updateId(record, data);
}
//We first make sure the primary data has been updated
//TODO try to move notification to the user to the end of the runloop
record.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {DS.Model} record
@param {Object} errors
*/
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {DS.Model} record
*/
recordWasError: function(record) {
record.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {DS.Model} record
@param {Object} data
*/
updateId: function(record, data) {
var oldId = ember$data$lib$system$store$$get(record, 'id');
var id = ember$data$lib$system$store$$coerceId(data.id);
Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);
this.typeMapFor(record.constructor).idToRecord[id] = record;
ember$data$lib$system$store$$set(record, 'id', id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param {subclass of DS.Model} type
@return {Object} typeMap
*/
typeMapFor: function(type) {
var typeMaps = ember$data$lib$system$store$$get(this, 'typeMaps');
var guid = Ember.guidFor(type);
var typeMap;
typeMap = typeMaps[guid];
if (typeMap) { return typeMap; }
typeMap = {
idToRecord: Ember.create(null),
records: [],
metadata: Ember.create(null),
type: type
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {String or subclass of DS.Model} type
@param {Object} data
*/
_load: function(type, data) {
var id = ember$data$lib$system$store$$coerceId(data.id);
var record = this.recordForId(type, id);
record.setupData(data);
this.recordArrayManager.recordDidChange(record);
return record;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String or subclass of DS.Model} key
@return {subclass of DS.Model}
*/
modelFor: function(key) {
var factory;
if (typeof key === 'string') {
factory = this.modelFactoryFor(key);
if (!factory) {
throw new Ember.Error("No model was found for '" + key + "'");
}
factory.typeKey = factory.typeKey || this._normalizeTypeKey(key);
} else {
// A factory already supplied. Ensure it has a normalized key.
factory = key;
if (factory.typeKey) {
factory.typeKey = this._normalizeTypeKey(factory.typeKey);
}
}
factory.store = this;
return factory;
},
modelFactoryFor: function(key) {
return this.container.lookupFactory('model:' + key);
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter, make sure
that you have converted the incoming data into this form. The
store's [normalize](#method_normalize) method is a convenience
helper for converting a json payload into the form Ember Data
expects.
```js
store.push('person', store.normalize('person', data));
```
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String or subclass of DS.Model} type
@param {Object} data
@return {DS.Model} the record that was created or
updated.
*/
push: function(typeName, data) {
Ember.assert("Expected an object as `data` in a call to `push` for " + typeName + " , but was " + data, Ember.typeOf(data) === 'object');
Ember.assert("You must include an `id` for " + typeName + " in an object passed to `push`", data.id != null && data.id !== '');
var type = this.modelFor(typeName);
var filter = Ember.EnumerableUtils.filter;
// If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload
// contains unknown keys, log a warning.
if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) {
Ember.warn("The payload for '" + type.typeKey + "' contains these unknown keys: " +
Ember.inspect(filter(Ember.keys(data), function(key) {
return !(key === 'id' || key === 'links' || ember$data$lib$system$store$$get(type, 'fields').has(key) || key.match(/Type$/));
})) + ". Make sure they've been defined in your model.",
filter(Ember.keys(data), function(key) {
return !(key === 'id' || key === 'links' || ember$data$lib$system$store$$get(type, 'fields').has(key) || key.match(/Type$/));
}).length === 0
);
}
// Actually load the record into the store.
this._load(type, data);
var record = this.recordForId(type, data.id);
var store = this;
this._backburner.join(function() {
store._backburner.schedule('normalizeRelationships', store, '_setupRelationships', record, type, data);
});
return record;
},
_setupRelationships: function(record, type, data) {
// If the payload contains relationships that are specified as
// IDs, normalizeRelationships will convert them into DS.Model instances
// (possibly unloaded) before we push the payload into the
// store.
data = ember$data$lib$system$store$$normalizeRelationships(this, type, data);
// Now that the pushed record as well as any related records
// are in the store, create the data structures used to track
// relationships.
ember$data$lib$system$store$$setupRelationships(this, record, data);
},
/**
Push some raw data into the store.
This method can be used both to push in brand new
records, as well as to update existing records. You
can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload(pushData);
```
By default, the data will be deserialized using a default
serializer (the application serializer if it exists).
Alternatively, `pushPayload` will accept a model type which
will determine which serializer will process the payload.
However, the serializer itself (processing this data via
`normalizePayload`) will not know which model it is
deserializing.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
App.PostSerializer = DS.JSONSerializer;
store.pushPayload('comment', pushData); // Will use the ApplicationSerializer
store.pushPayload('post', pushData); // Will use the PostSerializer
```
@method pushPayload
@param {String} type Optionally, a model used to determine which serializer will be used
@param {Object} payload
*/
pushPayload: function (type, inputPayload) {
var serializer;
var payload;
if (!inputPayload) {
payload = type;
serializer = ember$data$lib$system$store$$defaultSerializer(this.container);
Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function');
} else {
payload = inputPayload;
serializer = this.serializerFor(type);
}
var store = this;
ember$data$lib$system$store$$_adapterRun(this, function() {
serializer.pushPayload(store, payload);
});
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
Example
```js
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
store.push(modelName, store.normalize(modelName, data));
});
```
@method normalize
@param {String} type The name of the model type for this payload
@param {Object} payload
@return {Object} The normalized payload
*/
normalize: function (type, payload) {
var serializer = this.serializerFor(type);
var model = this.modelFor(type);
return serializer.normalize(model, payload);
},
/**
@method update
@param {String} type
@param {Object} data
@return {DS.Model} the record that was updated.
@deprecated Use [push](#method_push) instead
*/
update: function(type, data) {
Ember.deprecate('Using store.update() has been deprecated since store.push() now handles partial updates. You should use store.push() instead.');
return this.push(type, data);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String or subclass of DS.Model} type
@param {Array} datas
@return {Array}
*/
pushMany: function(type, datas) {
var length = datas.length;
var result = new Array(length);
for (var i = 0; i < length; i++) {
result[i] = this.push(type, datas[i]);
}
return result;
},
/**
@method metaForType
@param {String or subclass of DS.Model} typeName
@param {Object} metadata
@deprecated Use [setMetadataFor](#method_setMetadataFor) instead
*/
metaForType: function(typeName, metadata) {
Ember.deprecate('Using store.metaForType() has been deprecated. Use store.setMetadataFor() to set metadata for a specific type.');
this.setMetadataFor(typeName, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {subclass of DS.Model} type
@param {String} id
@param {Object} data
@return {DS.Model} record
*/
buildRecord: function(type, id, data) {
var typeMap = this.typeMapFor(type);
var idToRecord = typeMap.idToRecord;
Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]);
Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') );
// lookupFactory should really return an object that creates
// instances with the injections applied
var record = type._create({
id: id,
store: this,
container: this.container
});
if (data) {
record.setupData(data);
}
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = record;
}
typeMap.records.push(record);
return record;
},
//Called by the state machine to notify the store that the record is ready to be interacted with
recordWasLoaded: function(record) {
this.recordArrayManager.recordWasLoaded(record);
},
// ...............
// . DESTRUCTION .
// ...............
/**
@method dematerializeRecord
@private
@param {DS.Model} record
@deprecated Use [unloadRecord](#method_unloadRecord) instead
*/
dematerializeRecord: function(record) {
Ember.deprecate('Using store.dematerializeRecord() has been deprecated since it was intended for private use only. You should use store.unloadRecord() instead.');
this._dematerializeRecord(record);
},
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method _dematerializeRecord
@private
@param {DS.Model} record
*/
_dematerializeRecord: function(record) {
var type = record.constructor;
var typeMap = this.typeMapFor(type);
var id = ember$data$lib$system$store$$get(record, 'id');
record.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = ember$data$lib$system$store$$indexOf(typeMap.records, record);
typeMap.records.splice(loc, 1);
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns the adapter for a given type.
@method adapterFor
@private
@param {subclass of DS.Model} type
@return DS.Adapter
*/
adapterFor: function(type) {
var adapter;
var container = this.container;
if (container) {
adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application');
}
return adapter || ember$data$lib$system$store$$get(this, 'defaultAdapter');
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
If no `App.ApplicationSerializer` is found, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} type the record to serialize
@return {DS.Serializer}
*/
serializerFor: function(type) {
type = this.modelFor(type);
var adapter = this.adapterFor(type);
return ember$data$lib$system$store$$serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer);
},
willDestroy: function() {
var typeMaps = this.typeMaps;
var keys = Ember.keys(typeMaps);
var types = ember$data$lib$system$store$$map(keys, byType);
this.recordArrayManager.destroy();
ember$data$lib$system$store$$forEach(types, this.unloadAll, this);
function byType(entry) {
return typeMaps[entry]['type'];
}
},
/**
All typeKeys are camelCase internally. Changing this function may
require changes to other normalization hooks (such as typeForRoot).
@method _normalizeTypeKey
@private
@param {String} type
@return {String} if the adapter can generate one, an ID
*/
_normalizeTypeKey: function(key) {
return ember$data$lib$system$store$$camelize(ember$inflector$lib$system$string$$singularize(key));
}
});
function ember$data$lib$system$store$$normalizeRelationships(store, type, data, record) {
type.eachRelationship(function(key, relationship) {
var kind = relationship.kind;
var value = data[key];
if (kind === 'belongsTo') {
ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, value);
} else if (kind === 'hasMany') {
ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, value);
}
});
return data;
}
function ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, id) {
if (ember$data$lib$system$store$$isNone(id) || id instanceof ember$data$lib$system$model$model$$default) {
return;
}
Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being " + Ember.inspect(id) + ", but " + key + " is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.", !Ember.isArray(id));
var type;
if (typeof id === 'number' || typeof id === 'string') {
type = ember$data$lib$system$store$$typeFor(relationship, key, data);
data[key] = store.recordForId(type, id);
} else if (typeof id === 'object') {
// hasMany polymorphic
Ember.assert('Ember Data expected a number or string to represent the record(s) in the `' + relationship.key + '` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `' + relationship.key +'` property in your serializer\'s attrs object.', id.type);
data[key] = store.recordForId(id.type, id.id);
}
}
function ember$data$lib$system$store$$typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, ids) {
if (ember$data$lib$system$store$$isNone(ids)) {
return;
}
Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being '" + Ember.inspect(ids) + "', but " + key + " is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.", Ember.isArray(ids));
for (var i=0, l=ids.length; i<l; i++) {
ember$data$lib$system$store$$deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// Delegation to the adapter and promise management
function ember$data$lib$system$store$$serializerFor(container, type, defaultSerializer) {
return container.lookup('serializer:'+type) ||
container.lookup('serializer:application') ||
container.lookup('serializer:' + defaultSerializer) ||
container.lookup('serializer:-default');
}
function ember$data$lib$system$store$$defaultSerializer(container) {
return container.lookup('serializer:application') ||
container.lookup('serializer:-default');
}
function ember$data$lib$system$store$$serializerForAdapter(adapter, type) {
var serializer = adapter.serializer;
var defaultSerializer = adapter.defaultSerializer;
var container = adapter.container;
if (container && serializer === undefined) {
serializer = ember$data$lib$system$store$$serializerFor(container, type.typeKey, defaultSerializer);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function(store, type, payload) { return payload; }
};
}
return serializer;
}
function ember$data$lib$system$store$$_objectIsAlive(object) {
return !(ember$data$lib$system$store$$get(object, "isDestroyed") || ember$data$lib$system$store$$get(object, "isDestroying"));
}
function ember$data$lib$system$store$$_guard(promise, test) {
var guarded = promise['finally'](function() {
if (!test()) {
guarded._subscribers.length = 0;
}
});
return guarded;
}
function ember$data$lib$system$store$$_adapterRun(store, fn) {
return store._backburner.run(fn);
}
function ember$data$lib$system$store$$_bind(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return fn.apply(undefined, args);
};
}
function ember$data$lib$system$store$$_find(adapter, store, type, id, record) {
var promise = adapter.find(store, type, id, record);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#find of " + type + " with id: " + id;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
return promise.then(function(adapterPayload) {
Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload);
return ember$data$lib$system$store$$_adapterRun(store, function() {
var payload = serializer.extract(store, type, adapterPayload, id, 'find');
return store.push(type, payload);
});
}, function(error) {
var record = store.getById(type, id);
if (record) {
record.notFound();
if (ember$data$lib$system$store$$get(record, 'isEmpty')) {
store.unloadRecord(record);
}
}
throw error;
}, "DS: Extract payload of '" + type + "'");
}
function ember$data$lib$system$store$$_findMany(adapter, store, type, ids, records) {
var promise = adapter.findMany(store, type, ids, records);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findMany of " + type;
if (promise === undefined) {
throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
}
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
return promise.then(function(adapterPayload) {
return ember$data$lib$system$store$$_adapterRun(store, function() {
var payload = serializer.extract(store, type, adapterPayload, null, 'findMany');
Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
return store.pushMany(type, payload);
});
}, null, "DS: Extract payload of " + type);
}
function ember$data$lib$system$store$$_findHasMany(adapter, store, record, link, relationship) {
var promise = adapter.findHasMany(store, record, link, relationship);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, relationship.type);
var label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, record));
return promise.then(function(adapterPayload) {
return ember$data$lib$system$store$$_adapterRun(store, function() {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany');
Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
var records = store.pushMany(relationship.type, payload);
return records;
});
}, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type);
}
function ember$data$lib$system$store$$_findBelongsTo(adapter, store, record, link, relationship) {
var promise = adapter.findBelongsTo(store, record, link, relationship);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, relationship.type);
var label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, record));
return promise.then(function(adapterPayload) {
return ember$data$lib$system$store$$_adapterRun(store, function() {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo');
if (!payload) {
return null;
}
var record = store.push(relationship.type, payload);
return record;
});
}, null, "DS: Extract payload of " + record + " : " + relationship.type);
}
function ember$data$lib$system$store$$_findAll(adapter, store, type, sinceToken) {
var promise = adapter.findAll(store, type, sinceToken);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findAll of " + type;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
return promise.then(function(adapterPayload) {
ember$data$lib$system$store$$_adapterRun(store, function() {
var payload = serializer.extract(store, type, adapterPayload, null, 'findAll');
Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
});
store.didUpdateAll(type);
return store.all(type);
}, null, "DS: Extract payload of findAll " + type);
}
function ember$data$lib$system$store$$_findQuery(adapter, store, type, query, recordArray) {
var promise = adapter.findQuery(store, type, query, recordArray);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, type);
var label = "DS: Handle Adapter#findQuery of " + type;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
return promise.then(function(adapterPayload) {
var payload;
ember$data$lib$system$store$$_adapterRun(store, function() {
payload = serializer.extract(store, type, adapterPayload, null, 'findQuery');
Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
});
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + type);
}
function ember$data$lib$system$store$$_commit(adapter, store, operation, record) {
var type = record.constructor;
var promise = adapter[operation](store, type, record);
var serializer = ember$data$lib$system$store$$serializerForAdapter(adapter, type);
var label = "DS: Extract and notify about " + operation + " completion of " + record;
Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !==undefined);
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, store));
promise = ember$data$lib$system$store$$_guard(promise, ember$data$lib$system$store$$_bind(ember$data$lib$system$store$$_objectIsAlive, record));
return promise.then(function(adapterPayload) {
var payload;
ember$data$lib$system$store$$_adapterRun(store, function() {
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, ember$data$lib$system$store$$get(record, 'id'), operation);
} else {
payload = adapterPayload;
}
store.didSaveRecord(record, payload);
});
return record;
}, function(reason) {
if (reason instanceof ember$data$lib$system$adapter$$InvalidError) {
var errors = serializer.extractErrors(store, type, reason.errors, ember$data$lib$system$store$$get(record, 'id'));
store.recordWasInvalid(record, errors);
reason = new ember$data$lib$system$adapter$$InvalidError(errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
function ember$data$lib$system$store$$setupRelationships(store, record, data) {
var type = record.constructor;
type.eachRelationship(function(key, descriptor) {
var kind = descriptor.kind;
var value = data[key];
var relationship = record._relationships[key];
if (data.links && data.links[key]) {
relationship.updateLink(data.links[key]);
}
if (kind === 'belongsTo') {
if (value === undefined) {
return;
}
relationship.setCanonicalRecord(value);
} else if (kind === 'hasMany' && value) {
relationship.updateRecordsFromAdapter(value);
}
});
}
var ember$data$lib$system$store$$default = ember$data$lib$system$store$$Store;
function ember$data$lib$initializers$store$$initializeStore(container, application) {
Ember.deprecate('Specifying a custom Store for Ember Data on your global namespace as `App.Store` ' +
'has been deprecated. Please use `App.ApplicationStore` instead.', !(application && application.Store));
container.register('store:main', container.lookupFactory('store:application') || (application && application.Store) || ember$data$lib$system$store$$default);
// allow older names to be looked up
var proxy = new ember$data$lib$system$container_proxy$$default(container);
proxy.registerDeprecations([
{ deprecated: 'serializer:_default', valid: 'serializer:-default' },
{ deprecated: 'serializer:_rest', valid: 'serializer:-rest' },
{ deprecated: 'adapter:_rest', valid: 'adapter:-rest' }
]);
// new go forward paths
container.register('serializer:-default', ember$data$lib$serializers$json_serializer$$default);
container.register('serializer:-rest', ember$data$lib$serializers$rest_serializer$$default);
container.register('adapter:-rest', ember$data$lib$adapters$rest_adapter$$default);
// Eagerly generate the store so defaultStore is populated.
// TODO: Do this in a finisher hook
container.lookup('store:main');
}
var ember$data$lib$initializers$store$$default = ember$data$lib$initializers$store$$initializeStore;
var ember$data$lib$transforms$base$$default = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param {mixed} deserialized The deserialized value
@return {mixed} The serialized value
*/
serialize: Ember.required(),
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param {mixed} serialized The serialized value
@return {mixed} The deserialized value
*/
deserialize: Ember.required()
});
var ember$data$lib$transforms$number$$empty = Ember.isEmpty;
function ember$data$lib$transforms$number$$isNumber(value) {
return value === value && value !== Infinity && value !== -Infinity;
}
var ember$data$lib$transforms$number$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function(serialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(serialized)) {
return null;
} else {
transformed = Number(serialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
},
serialize: function(deserialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(deserialized)) {
return null;
} else {
transformed = Number(deserialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
}
});
// Date.prototype.toISOString shim
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
var ember$data$lib$transforms$date$$toISOString = Date.prototype.toISOString || function() {
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
if (Ember.SHIM_ES5) {
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = ember$data$lib$transforms$date$$toISOString;
}
}
var ember$data$lib$transforms$date$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "string") {
return new Date(Ember.Date.parse(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
serialize: function(date) {
if (date instanceof Date) {
return ember$data$lib$transforms$date$$toISOString.call(date);
} else {
return null;
}
}
});
var ember$data$lib$transforms$string$$none = Ember.isNone;
var ember$data$lib$transforms$string$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function(serialized) {
return ember$data$lib$transforms$string$$none(serialized) ? null : String(serialized);
},
serialize: function(deserialized) {
return ember$data$lib$transforms$string$$none(deserialized) ? null : String(deserialized);
}
});
var ember$data$lib$transforms$boolean$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function(deserialized) {
return Boolean(deserialized);
}
});
function ember$data$lib$initializers$transforms$$initializeTransforms(container) {
container.register('transform:boolean', ember$data$lib$transforms$boolean$$default);
container.register('transform:date', ember$data$lib$transforms$date$$default);
container.register('transform:number', ember$data$lib$transforms$number$$default);
container.register('transform:string', ember$data$lib$transforms$string$$default);
}
var ember$data$lib$initializers$transforms$$default = ember$data$lib$initializers$transforms$$initializeTransforms;
function ember$data$lib$initializers$store_injections$$initializeStoreInjections(container) {
container.injection('controller', 'store', 'store:main');
container.injection('route', 'store', 'store:main');
container.injection('serializer', 'store', 'store:main');
container.injection('data-adapter', 'store', 'store:main');
}
var ember$data$lib$initializers$store_injections$$default = ember$data$lib$initializers$store_injections$$initializeStoreInjections;
var ember$data$lib$system$debug$debug_adapter$$get = Ember.get;
var ember$data$lib$system$debug$debug_adapter$$capitalize = Ember.String.capitalize;
var ember$data$lib$system$debug$debug_adapter$$underscore = Ember.String.underscore;
var ember$data$lib$system$debug$debug_adapter$$default = Ember.DataAdapter.extend({
getFilters: function() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect: function(klass) {
return klass !== ember$data$lib$system$model$model$$default && ember$data$lib$system$model$model$$default.detect(klass);
},
columnsForType: function(type) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
ember$data$lib$system$debug$debug_adapter$$get(type, 'attributes').forEach(function(meta, name) {
if (count++ > self.attributeLimit) { return false; }
var desc = ember$data$lib$system$debug$debug_adapter$$capitalize(ember$data$lib$system$debug$debug_adapter$$underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function(type) {
return this.get('store').all(type);
},
getRecordColumnValues: function(record) {
var self = this;
var count = 0;
var columnValues = { id: ember$data$lib$system$debug$debug_adapter$$get(record, 'id') };
record.eachAttribute(function(key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = ember$data$lib$system$debug$debug_adapter$$get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function(record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute(function(key) {
keys.push(key);
});
keys.forEach(function(key) {
keywords.push(ember$data$lib$system$debug$debug_adapter$$get(record, key));
});
return keywords;
},
getRecordFilterValues: function(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function(record, recordUpdated) {
var releaseMethods = Ember.A();
var self = this;
var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function(key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach(function(fn) { fn(); } );
};
return release;
}
});
function ember$data$lib$initializers$data_adapter$$initializeDebugAdapter(container) {
container.register('data-adapter:main', ember$data$lib$system$debug$debug_adapter$$default);
}
var ember$data$lib$initializers$data_adapter$$default = ember$data$lib$initializers$data_adapter$$initializeDebugAdapter;
function ember$data$lib$setup$container$$setupContainer(container, application) {
// application is not a required argument. This ensures
// testing setups can setup a container without booting an
// entire ember application.
ember$data$lib$initializers$data_adapter$$default(container, application);
ember$data$lib$initializers$transforms$$default(container, application);
ember$data$lib$initializers$store_injections$$default(container, application);
ember$data$lib$initializers$store$$default(container, application);
activemodel$adapter$lib$setup$container$$default(container, application);
}
var ember$data$lib$setup$container$$default = ember$data$lib$setup$container$$setupContainer;
var ember$data$lib$ember$initializer$$K = Ember.K;
/**
@module ember-data
*/
/*
This code initializes Ember-Data onto an Ember application.
If an Ember.js developer defines a subclass of DS.Store on their application,
as `App.ApplicationStore` (or via a module system that resolves to `store:application`)
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.ApplicationStore = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.ApplicationStore` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "ember-data",
initialize: ember$data$lib$setup$container$$default
});
// Deprecated initializers to satisfy old code that depended on them
Application.initializer({
name: "store",
after: "ember-data",
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: "activeModelAdapter",
before: "store",
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: "transforms",
before: "store",
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: "data-adapter",
before: "store",
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: "injectStore",
before: "store",
initialize: ember$data$lib$ember$initializer$$K
});
});
/**
@module ember-data
*/
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
*/
Ember.Date = Ember.Date || {};
var origParse = Date.parse;
var numericKeys = [1, 4, 5, 6, 7, 10, 11];
/**
@method parse
@param {Date} date
@return {Number} timestamp
*/
Ember.Date.parse = function (date) {
var timestamp, struct;
var minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
} else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
ember$data$lib$system$model$model$$default.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function() {
var attributes = ['id'];
var relationships = { belongsTo: [], hasMany: [] };
var expensiveProperties = [];
this.eachAttribute(function(name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function(name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
},
{
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
},
{
name: 'Has Many',
properties: relationships.hasMany,
expand: true
},
{
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}
];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
var ember$data$lib$system$debug$debug_info$$default = ember$data$lib$system$model$model$$default;
var ember$data$lib$system$debug$$default = ember$data$lib$system$debug$debug_adapter$$default;
var ember$data$lib$serializers$embedded_records_mixin$$get = Ember.get;
var ember$data$lib$serializers$embedded_records_mixin$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$serializers$embedded_records_mixin$$camelize = Ember.String.camelize;
/**
## Using Embedded Records
`DS.EmbeddedRecordsMixin` supports serializing embedded records.
To set up embedded records, include the mixin when extending a serializer
then define and configure embedded (model) relationships.
Below is an example of a per-type serializer ('post' type).
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: { embedded: 'always' },
comments: { serialize: 'ids' }
}
});
```
Note that this use of `{ embedded: 'always' }` is unrelated to
the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of
defining a model while working with the ActiveModelSerializer. Nevertheless,
using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup
embedded records.
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
```js
{
serialize: 'records',
deserialize: 'records'
}
```
### Configuring Attrs
A resource's `attrs` option may be set to use `ids`, `records` or false for the
`serialize` and `deserialize` settings.
The `attrs` property can be set on the ApplicationSerializer or a per-type
serializer.
In the case where embedded JSON is expected while extracting a payload (reading)
the setting is `deserialize: 'records'`, there is no need to use `ids` when
extracting as that is the default behavior without this mixin if you are using
the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while
serializing `serialize: 'records'` is the setting to use. There is an option of
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
do not want the relationship sent at all, you can use `serialize: false`.
### EmbeddedRecordsMixin defaults
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
will behave in the following way:
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
HasMany: `{ serialize: false, deserialize: 'ids' }`
### Model Relationships
Embedded records must have a model defined to be extracted and serialized. Note that
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
should not both specify `async:true` and also indicate through the serializer's
`attrs` attribute that the related model should be embedded. If a model is
declared embedded, then do not use `async:true`.
To successfully extract and serialize embedded records the model relationships
must be setup correcty See the
[defining relationships](/guides/models/defining-models/#toc_defining-relationships)
section of the **Defining Models** guide page.
Records without an `id` property are not considered embedded records, model
instances must have an `id` property to be used with Ember Data.
### Example JSON payloads, Models and Serializers
**When customizing a serializer it is important to grok what the customizations
are. Please read the docs for the methods this mixin provides, in case you need
to modify it to fit your specific needs.**
For example review the docs for each method of this mixin:
* [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize)
* [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo)
* [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany)
@class EmbeddedRecordsMixin
@namespace DS
*/
var ember$data$lib$serializers$embedded_records_mixin$$EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Normalize the record and recursively normalize/extract all the embedded records
while pushing them into the store as they are encountered
A payload with an attr configured for embedded records needs to be extracted:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash to be normalized
@param {String} key the hash has been referenced by
@return {Object} the normalized hash
**/
normalize: function(type, hash, prop) {
var normalizedHash = this._super(type, hash, prop);
return ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedRecords(this, this.store, type, normalizedHash);
},
keyForRelationship: function(key, type) {
if (this.hasDeserializeRecordsOption(key)) {
return this.keyForAttribute(key);
} else {
return this._super(key, type) || key;
}
},
/**
Serialize `belongsTo` relationship when it is configured as an embedded object.
This example of an author model belongs to a post model:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
author: DS.belongsTo('author')
});
Author = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded author
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"author": {
"id": "2"
"name": "dhh"
}
}
}
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var embeddedSnapshot = snapshot.belongsTo(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind);
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.id;
}
} else if (includeRecords) {
key = this.keyForAttribute(attr);
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key]);
}
}
},
/**
Serialize `hasMany` relationship when it is configured as embedded objects.
This example of a post model has many comments:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded comments
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
The attrs options object can use more specific instruction for extracting and
serializing. When serializing, an option to embed `ids` or `records` can be set.
When extracting the only option is `records`.
So `{embedded: 'always'}` is shorthand for:
`{serialize: 'records', deserialize: 'records'}`
To embed the `ids` for a related object (using a hasMany relationship):
```js
App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {serialize: 'ids', deserialize: 'records'}
}
})
```
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": ["1", "2"]
}
}
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind);
json[key] = snapshot.hasMany(attr, { ids: true });
} else if (includeRecords) {
key = this.keyForAttribute(attr);
json[key] = snapshot.hasMany(attr).map(function(embeddedSnapshot) {
var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
return embeddedJson;
}, this);
}
},
/**
When serializing an embedded record, modify the property (in the json payload)
that refers to the parent record (foreign key for relationship).
Serializing a `belongsTo` relationship removes the property that refers to the
parent record
Serializing a `hasMany` relationship does not remove the property that refers to
the parent record.
@method removeEmbeddedForeignKey
@param {DS.Snapshot} snapshot
@param {DS.Snapshot} embeddedSnapshot
@param {Object} relationship
@param {Object} json
*/
removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) {
if (relationship.kind === 'hasMany') {
return;
} else if (relationship.kind === 'belongsTo') {
var parentRecord = snapshot.type.inverseFor(relationship.key);
if (parentRecord) {
var name = parentRecord.name;
var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.type);
var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind);
if (parentKey) {
delete json[parentKey];
}
}
}
},
// checks config for attrs option to embedded (always) - serialize and deserialize
hasEmbeddedAlwaysOption: function (attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// checks config for attrs option to serialize ids
hasSerializeRecordsOption: function(attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || (option && (option.serialize === 'records'));
},
// checks config for attrs option to serialize records
hasSerializeIdsOption: function(attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids' || option.serialize === 'id');
},
// checks config for attrs option to serialize records
noSerializeOptionSpecified: function(attr) {
var option = this.attrsOption(attr);
return !(option && (option.serialize || option.embedded));
},
// checks config for attrs option to deserialize records
// a defined option object for a resource is treated the same as
// `deserialize: 'records'`
hasDeserializeRecordsOption: function(attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || (option && option.deserialize === 'records');
},
attrsOption: function(attr) {
var attrs = this.get('attrs');
return attrs && (attrs[ember$data$lib$serializers$embedded_records_mixin$$camelize(attr)] || attrs[attr]);
}
});
// chooses a relationship kind to branch which function is used to update payload
// does not change payload if attr is not embedded
function ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedRecords(serializer, store, type, partial) {
type.eachRelationship(function(key, relationship) {
if (serializer.hasDeserializeRecordsOption(key)) {
var embeddedType = store.modelFor(relationship.type.typeKey);
if (relationship.kind === "hasMany") {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedHasManyPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedHasMany(store, key, embeddedType, partial);
}
}
if (relationship.kind === "belongsTo") {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedBelongsToPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedBelongsTo(store, key, embeddedType, partial);
}
}
}
});
return partial;
}
// handles embedding for `hasMany` relationship
function ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedHasMany(store, key, embeddedType, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
var embeddedSerializer = store.serializerFor(embeddedType.typeKey);
ember$data$lib$serializers$embedded_records_mixin$$forEach(hash[key], function(data) {
var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null);
store.push(embeddedType, embeddedRecord);
ids.push(embeddedRecord.id);
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedHasManyPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
ember$data$lib$serializers$embedded_records_mixin$$forEach(hash[key], function(data) {
var typeKey = data.type;
var embeddedSerializer = store.serializerFor(typeKey);
var embeddedType = store.modelFor(typeKey);
var primaryKey = ember$data$lib$serializers$embedded_records_mixin$$get(embeddedSerializer, 'primaryKey');
var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null);
store.push(embeddedType, embeddedRecord);
ids.push({ id: embeddedRecord[primaryKey], type: typeKey });
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedBelongsTo(store, key, embeddedType, hash) {
if (!hash[key]) {
return hash;
}
var embeddedSerializer = store.serializerFor(embeddedType.typeKey);
var embeddedRecord = embeddedSerializer.normalize(embeddedType, hash[key], null);
store.push(embeddedType, embeddedRecord);
hash[key] = embeddedRecord.id;
//TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records
return hash;
}
function ember$data$lib$serializers$embedded_records_mixin$$extractEmbeddedBelongsToPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var data = hash[key];
var typeKey = data.type;
var embeddedSerializer = store.serializerFor(typeKey);
var embeddedType = store.modelFor(typeKey);
var primaryKey = ember$data$lib$serializers$embedded_records_mixin$$get(embeddedSerializer, 'primaryKey');
var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null);
store.push(embeddedType, embeddedRecord);
hash[key] = embeddedRecord[primaryKey];
hash[key + 'Type'] = typeKey;
return hash;
}
var ember$data$lib$serializers$embedded_records_mixin$$default = ember$data$lib$serializers$embedded_records_mixin$$EmbeddedRecordsMixin;
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```javascript
App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the key name.
```javascript
App.Comment = DS.Model.extend({
post: DS.belongsTo()
});
```
will lookup for a Post type.
@namespace
@method belongsTo
@for DS
@param {String} type (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$belongs_to$$belongsTo(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + Ember.inspect(type) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof type === 'string' || typeof type === 'undefined');
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'belongsTo',
key: null
};
return Ember.computed(function(key, value) {
if (arguments.length>1) {
if ( value === undefined ) {
value = null;
}
if (value && value.then) {
this._relationships[key].setRecordPromise(value);
} else {
this._relationships[key].setRecord(value);
}
}
return this._relationships[key].getRecord();
}).meta(meta);
}
/*
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
*/
ember$data$lib$system$model$model$$default.reopen({
notifyBelongsToChanged: function(key) {
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$belongs_to$$default = ember$data$lib$system$relationships$belongs_to$$belongsTo;
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
posts: DS.hasMany('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the singularized key name.
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany()
});
```
will lookup for a Tag type.
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```javascript
var belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Comment = DS.Model.extend({
onePost: belongsTo('post'),
twoPost: belongsTo('post'),
redPost: belongsTo('post'),
bluePost: belongsTo('post')
});
App.Post = DS.Model.extend({
comments: hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String} type (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$has_many$$hasMany(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
Ember.assert("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + Ember.inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === 'string' || typeof type === 'undefined');
options = options || {};
// Metadata about relationships is stored on the meta of
// the relationship. This is used for introspection and
// serialization. Note that `key` is populated lazily
// the first time the CP is called.
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'hasMany',
key: null
};
return Ember.computed(function(key) {
var relationship = this._relationships[key];
return relationship.getRecords();
}).meta(meta).readOnly();
}
ember$data$lib$system$model$model$$default.reopen({
notifyHasManyAdded: function(key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$has_many$$default = ember$data$lib$system$relationships$has_many$$hasMany;
function ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(store, meta) {
var typeKey, type;
typeKey = meta.type || meta.key;
if (typeof typeKey === 'string') {
if (meta.kind === 'hasMany') {
typeKey = ember$inflector$lib$system$string$$singularize(typeKey);
}
type = store.modelFor(typeKey);
} else {
type = meta.type;
}
return type;
}
function ember$data$lib$system$relationship$meta$$relationshipFromMeta(store, meta) {
return {
key: meta.key,
kind: meta.kind,
type: ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(store, meta),
options: meta.options,
parentType: meta.parentType,
isRelationship: true
};
}
var ember$data$lib$system$relationships$ext$$get = Ember.get;
var ember$data$lib$system$relationships$ext$$filter = Ember.ArrayPolyfills.filter;
var ember$data$lib$system$relationships$ext$$relationshipsDescriptor = Ember.computed(function() {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable = false;
}
var map = new ember$data$lib$system$map$$MapWithDefault({
defaultValue: function() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty(function(name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get(ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relatedTypesDescriptor = Ember.computed(function() {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable = false;
}
var type;
var types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta);
Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type);
if (!types.contains(type)) {
Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type);
types.push(type);
}
}
});
return types;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor = Ember.computed(function() {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable = false;
}
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
var relationship = ember$data$lib$system$relationship$meta$$relationshipFromMeta(this.store, meta);
relationship.type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta);
map.set(name, relationship);
}
});
return map;
}).readOnly();
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$model$$default.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty: function(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
ember$data$lib$system$model$model$$default.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@return {subclass of DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function(name) {
var relationship = ember$data$lib$system$relationships$ext$$get(this, 'relationshipsByName').get(name);
return relationship && relationship.type;
},
inverseMap: Ember.computed(function() {
return Ember.create(null);
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('message')
});
App.Message = DS.Model.extend({
owner: DS.belongsTo('post')
});
```
App.Post.inverseFor('comments') -> {type: App.Message, name:'owner', kind:'belongsTo'}
App.Message.inverseFor('owner') -> {type: App.Post, name:'comments', kind:'hasMany'}
@method inverseFor
@static
@param {String} name the name of the relationship
@return {Object} the inverse relationship, or null
*/
inverseFor: function(name) {
var inverseMap = ember$data$lib$system$relationships$ext$$get(this, 'inverseMap');
if (inverseMap[name]) {
return inverseMap[name];
} else {
var inverse = this._findInverseFor(name);
inverseMap[name] = inverse;
return inverse;
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor: function(name) {
var inverseType = this.typeForRelationship(name);
if (!inverseType) {
return null;
}
var propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', {inverse: null})`
var options = propertyMeta.options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind, inverse;
Ember.warn("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.", options.inverse || propertyMeta.type !== propertyMeta.parentType.typeKey);
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName);
Ember.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.typeKey +
"' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse));
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
var filteredRelationships = ember$data$lib$system$relationships$ext$$filter.call(possibleRelationships, function(possibleRelationship) {
var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " +
inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
filteredRelationships.length < 2);
if (filteredRelationships.length === 1 ) {
possibleRelationships = filteredRelationships;
}
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " +
this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, relationshipsSoFar) {
var possibleRelationships = relationshipsSoFar || [];
var relationshipMap = ember$data$lib$system$relationships$ext$$get(inverseType, 'relationships');
if (!relationshipMap) { return; }
var relationships = relationshipMap.get(type);
relationships = ember$data$lib$system$relationships$ext$$filter.call(relationships, function(relationship) {
var optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: ember$data$lib$system$relationships$ext$$relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: ember$data$lib$system$relationships$ext$$relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, 'relationshipsByName').forEach(function(relationship, name) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function(callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, 'relatedTypes').forEach(function(type) {
callback.call(binding, type);
});
},
determineRelationshipType: function(knownSide) {
var knownKey = knownSide.key;
var knownKind = knownSide.kind;
var inverse = this.inverseFor(knownKey);
var key, otherKind;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
}
});
ember$data$lib$system$model$model$$default.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">DS.Model</span> the type of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
var serializedHasManyName = name.toUpperCase() + '_IDS';
json[name.toUpperCase()] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor: function(name) {
return ember$data$lib$system$relationships$ext$$get(this.constructor, 'relationshipsByName').get(name);
},
inverseFor: function(key) {
return this.constructor.inverseFor(key);
}
});
/**
Ember Data
@module ember-data
@main ember-data
*/
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;
Ember.runInDebug(function() {
if (Ember.VERSION.match(/1\.[0-7]\./)) {
throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have " +
Ember.VERSION +
". Please upgrade your version of Ember, then upgrade Ember Data");
}
});
ember$data$lib$core$$default.Store = ember$data$lib$system$store$$Store;
ember$data$lib$core$$default.PromiseArray = ember$data$lib$system$promise_proxies$$PromiseArray;
ember$data$lib$core$$default.PromiseObject = ember$data$lib$system$promise_proxies$$PromiseObject;
ember$data$lib$core$$default.PromiseManyArray = ember$data$lib$system$promise_proxies$$PromiseManyArray;
ember$data$lib$core$$default.Model = ember$data$lib$system$model$model$$default;
ember$data$lib$core$$default.RootState = ember$data$lib$system$model$states$$default;
ember$data$lib$core$$default.attr = ember$data$lib$system$model$attributes$$default;
ember$data$lib$core$$default.Errors = ember$data$lib$system$model$errors$$default;
ember$data$lib$core$$default.Snapshot = ember$data$lib$system$snapshot$$default;
ember$data$lib$core$$default.Adapter = ember$data$lib$system$adapter$$Adapter;
ember$data$lib$core$$default.InvalidError = ember$data$lib$system$adapter$$InvalidError;
ember$data$lib$core$$default.Serializer = ember$data$lib$system$serializer$$default;
ember$data$lib$core$$default.DebugAdapter = ember$data$lib$system$debug$$default;
ember$data$lib$core$$default.RecordArray = ember$data$lib$system$record_arrays$record_array$$default;
ember$data$lib$core$$default.FilteredRecordArray = ember$data$lib$system$record_arrays$filtered_record_array$$default;
ember$data$lib$core$$default.AdapterPopulatedRecordArray = ember$data$lib$system$record_arrays$adapter_populated_record_array$$default;
ember$data$lib$core$$default.ManyArray = ember$data$lib$system$record_arrays$many_array$$default;
ember$data$lib$core$$default.RecordArrayManager = ember$data$lib$system$record_array_manager$$default;
ember$data$lib$core$$default.RESTAdapter = ember$data$lib$adapters$rest_adapter$$default;
ember$data$lib$core$$default.FixtureAdapter = ember$data$lib$adapters$fixture_adapter$$default;
ember$data$lib$core$$default.RESTSerializer = ember$data$lib$serializers$rest_serializer$$default;
ember$data$lib$core$$default.JSONSerializer = ember$data$lib$serializers$json_serializer$$default;
ember$data$lib$core$$default.Transform = ember$data$lib$transforms$base$$default;
ember$data$lib$core$$default.DateTransform = ember$data$lib$transforms$date$$default;
ember$data$lib$core$$default.StringTransform = ember$data$lib$transforms$string$$default;
ember$data$lib$core$$default.NumberTransform = ember$data$lib$transforms$number$$default;
ember$data$lib$core$$default.BooleanTransform = ember$data$lib$transforms$boolean$$default;
ember$data$lib$core$$default.ActiveModelAdapter = activemodel$adapter$lib$system$active_model_adapter$$default;
ember$data$lib$core$$default.ActiveModelSerializer = activemodel$adapter$lib$system$active_model_serializer$$default;
ember$data$lib$core$$default.EmbeddedRecordsMixin = ember$data$lib$serializers$embedded_records_mixin$$default;
ember$data$lib$core$$default.belongsTo = ember$data$lib$system$relationships$belongs_to$$default;
ember$data$lib$core$$default.hasMany = ember$data$lib$system$relationships$has_many$$default;
ember$data$lib$core$$default.Relationship = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$core$$default.ContainerProxy = ember$data$lib$system$container_proxy$$default;
ember$data$lib$core$$default._setupContainer = ember$data$lib$setup$container$$default;
Ember.lookup.DS = ember$data$lib$core$$default;
var ember$data$lib$main$$default = ember$data$lib$core$$default;
}).call(this);
//# sourceMappingURL=ember-data.js.map |
src/views/app.js | r-park/soundcloud-redux | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, withRouter } from 'react-router-dom';
import { createSelector } from 'reselect';
import { getSearch, searchActions } from 'src/core/search/index';
import AppHeader from './components/app-header';
import Player from './components/player';
import HomePage from './pages/home-page';
import SearchPage from './pages/search-page';
import UserPage from './pages/user-page';
export function App({handleSearch, search, toggleSearch}) {
return (
<div>
<AppHeader
handleSearch={handleSearch}
search={search}
toggleSearch={toggleSearch}
/>
<main className="main">
<Route exact path="/" component={HomePage}/>
<Route path="/search" component={SearchPage}/>
<Route path="/users/:id/:resource" component={UserPage}/>
</main>
<Player />
</div>
);
}
App.propTypes = {
children: PropTypes.element,
handleSearch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired,
toggleSearch: PropTypes.func.isRequired
};
//=====================================
// CONNECT
//-------------------------------------
const mapStateToProps = createSelector(
getSearch,
search => ({
search: search.toJS()
})
);
const mapDispatchToProps = {
handleSearch: searchActions.navigateToSearch,
toggleSearch: searchActions.toggleSearchField
};
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(App)
);
|
packager/react-packager/src/Server/index.js | milieu/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var url = require('url');
var path = require('path');
var declareOpts = require('../lib/declareOpts');
var FileWatcher = require('../FileWatcher');
var Packager = require('../Packager');
var Activity = require('../Activity');
var AssetServer = require('../AssetServer');
var Promise = require('promise');
var _ = require('underscore');
var exec = require('child_process').exec;
var fs = require('fs');
module.exports = Server;
var validateOpts = declareOpts({
projectRoots: {
type: 'array',
required: true,
},
blacklistRE: {
type: 'object', // typeof regex is object
},
moduleFormat: {
type: 'string',
default: 'haste',
},
polyfillModuleNames: {
type: 'array',
default: [],
},
cacheVersion: {
type: 'string',
default: '1.0',
},
resetCache: {
type: 'boolean',
default: false,
},
transformModulePath: {
type:'string',
required: false,
},
nonPersistent: {
type: 'boolean',
default: false,
},
assetRoots: {
type: 'array',
required: false,
},
assetExts: {
type: 'array',
default: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'],
},
});
function Server(options) {
var opts = validateOpts(options);
this._projectRoots = opts.projectRoots;
this._packages = Object.create(null);
this._changeWatchers = [];
var assetGlobs = opts.assetExts.map(function(ext) {
return '**/*.' + ext;
});
var watchRootConfigs = opts.projectRoots.map(function(dir) {
return {
dir: dir,
globs: [
'**/*.js',
'**/*.json',
].concat(assetGlobs),
};
});
if (opts.assetRoots != null) {
watchRootConfigs = watchRootConfigs.concat(
opts.assetRoots.map(function(dir) {
return {
dir: dir,
globs: assetGlobs,
};
})
);
}
this._fileWatcher = options.nonPersistent
? FileWatcher.createDummyWatcher()
: new FileWatcher(watchRootConfigs);
this._assetServer = new AssetServer({
projectRoots: opts.projectRoots,
assetExts: opts.assetExts,
});
var packagerOpts = Object.create(opts);
packagerOpts.fileWatcher = this._fileWatcher;
packagerOpts.assetServer = this._assetServer;
this._packager = new Packager(packagerOpts);
var onFileChange = this._onFileChange.bind(this);
this._fileWatcher.on('all', onFileChange);
var self = this;
this._debouncedFileChangeHandler = _.debounce(function(filePath) {
self._rebuildPackages(filePath);
self._informChangeWatchers();
}, 50);
}
Server.prototype._onFileChange = function(type, filepath, root) {
var absPath = path.join(root, filepath);
this._packager.invalidateFile(absPath);
// Make sure the file watcher event runs through the system before
// we rebuild the packages.
this._debouncedFileChangeHandler(absPath);
};
Server.prototype._rebuildPackages = function() {
var buildPackage = this.buildPackage.bind(this);
var packages = this._packages;
Object.keys(packages).forEach(function(optionsJson) {
var options = JSON.parse(optionsJson);
// Wait for a previous build (if exists) to finish.
packages[optionsJson] = (packages[optionsJson] || Promise.resolve()).finally(function() {
// With finally promise callback we can't change the state of the promise
// so we need to reassign the promise.
packages[optionsJson] = buildPackage(options).then(function(p) {
// Make a throwaway call to getSource to cache the source string.
p.getSource({
inlineSourceMap: options.inlineSourceMap,
minify: options.minify,
});
return p;
});
});
return packages[optionsJson];
});
};
Server.prototype._informChangeWatchers = function() {
var watchers = this._changeWatchers;
var headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
watchers.forEach(function(w) {
w.res.writeHead(205, headers);
w.res.end(JSON.stringify({ changed: true }));
});
this._changeWatchers = [];
};
Server.prototype.end = function() {
Promise.all([
this._fileWatcher.end(),
this._packager.kill(),
]);
};
var packageOpts = declareOpts({
sourceMapUrl: {
type: 'string',
required: false,
},
entryFile: {
type: 'string',
required: true,
},
dev: {
type: 'boolean',
default: true,
},
minify: {
type: 'boolean',
default: false,
},
runModule: {
type: 'boolean',
default: true,
},
inlineSourceMap: {
type: 'boolean',
default: false,
},
});
Server.prototype.buildPackage = function(options) {
var opts = packageOpts(options);
return this._packager.package(
opts.entryFile,
opts.runModule,
opts.sourceMapUrl,
opts.dev
);
};
Server.prototype.buildPackageFromUrl = function(reqUrl) {
var options = getOptionsFromUrl(reqUrl);
return this.buildPackage(options);
};
Server.prototype.getDependencies = function(main) {
return this._packager.getDependencies(main);
};
Server.prototype._processDebugRequest = function(reqUrl, res) {
var ret = '<!doctype html>';
var pathname = url.parse(reqUrl).pathname;
var parts = pathname.split('/').filter(Boolean);
if (parts.length === 1) {
ret += '<div><a href="/debug/packages">Cached Packages</a></div>';
ret += '<div><a href="/debug/graph">Dependency Graph</a></div>';
res.end(ret);
} else if (parts[1] === 'packages') {
ret += '<h1> Cached Packages </h1>';
Promise.all(Object.keys(this._packages).map(function(optionsJson) {
return this._packages[optionsJson].then(function(p) {
ret += '<div><h2>' + optionsJson + '</h2>';
ret += p.getDebugInfo();
});
}, this)).then(
function() { res.end(ret); },
function(e) {
res.writeHead(500);
res.end('Internal Error');
console.log(e.stack);
}
);
} else if (parts[1] === 'graph'){
ret += '<h1> Dependency Graph </h2>';
ret += this._packager.getGraphDebugInfo();
res.end(ret);
} else {
res.writeHead('404');
res.end('Invalid debug request');
return;
}
};
Server.prototype._processOnChangeRequest = function(req, res) {
var watchers = this._changeWatchers;
watchers.push({
req: req,
res: res,
});
req.on('close', function() {
for (var i = 0; i < watchers.length; i++) {
if (watchers[i] && watchers[i].req === req) {
watchers.splice(i, 1);
break;
}
}
});
};
Server.prototype._processAssetsRequest = function(req, res) {
var urlObj = url.parse(req.url, true);
var assetPath = urlObj.pathname.match(/^\/assets\/(.+)$/);
this._assetServer.get(assetPath[1])
.then(
function(data) {
res.end(data);
},
function(error) {
console.error(error.stack);
res.writeHead('404');
res.end('Asset not found');
}
).done();
};
Server.prototype._processProfile = function(req, res) {
console.log('Dumping profile information...');
var dumpName = '/tmp/dump_' + Date.now() + '.json';
var prefix = process.env.TRACE_VIEWER_PATH || '';
var cmd = path.join(prefix, 'trace2html') + ' ' + dumpName;
fs.writeFileSync(dumpName, req.rawBody);
exec(cmd, function (error) {
if (error) {
if (error.code === 127) {
console.error(
'\n** Failed executing `' + cmd + '` **\n\n' +
'Google trace-viewer is required to visualize the data, do you have it installled?\n\n' +
'You can get it at:\n\n' +
' https://github.com/google/trace-viewer\n\n' +
'If it\'s not in your path, you can set a custom path with:\n\n' +
' TRACE_VIEWER_PATH=/path/to/trace-viewer\n\n' +
'NOTE: Your profile data was kept at:\n\n' +
' ' + dumpName
);
} else {
console.error('Unknown error', error);
}
res.end();
return;
} else {
exec('rm ' + dumpName);
exec('open ' + dumpName.replace(/json$/, 'html'), function (error) {
if (error) {
console.error(error);
}
res.end();
});
}
});
};
Server.prototype.processRequest = function(req, res, next) {
var urlObj = url.parse(req.url, true);
var pathname = urlObj.pathname;
var requestType;
if (pathname.match(/\.bundle$/)) {
requestType = 'bundle';
} else if (pathname.match(/\.map$/)) {
requestType = 'map';
} else if (pathname.match(/^\/debug/)) {
this._processDebugRequest(req.url, res);
return;
} else if (pathname.match(/^\/onchange\/?$/)) {
this._processOnChangeRequest(req, res);
return;
} else if (pathname.match(/^\/assets\//)) {
this._processAssetsRequest(req, res);
return;
} else if (pathname.match(/^\/profile\/?$/)) {
this._processProfile(req, res);
return;
} else {
next();
return;
}
var startReqEventId = Activity.startEvent('request:' + req.url);
var options = getOptionsFromUrl(req.url);
var optionsJson = JSON.stringify(options);
var building = this._packages[optionsJson] || this.buildPackage(options);
this._packages[optionsJson] = building;
building.then(
function(p) {
if (requestType === 'bundle') {
var bundleSource = p.getSource({
inlineSourceMap: options.inlineSourceMap,
minify: options.minify,
});
res.setHeader('Content-Type', 'application/javascript');
res.end(bundleSource);
Activity.endEvent(startReqEventId);
} else if (requestType === 'map') {
var sourceMap = JSON.stringify(p.getSourceMap());
res.setHeader('Content-Type', 'application/json');
res.end(sourceMap);
Activity.endEvent(startReqEventId);
}
},
function(error) {
handleError(res, error);
}
).done();
};
function getOptionsFromUrl(reqUrl) {
// `true` to parse the query param as an object.
var urlObj = url.parse(reqUrl, true);
// node v0.11.14 bug see https://github.com/facebook/react-native/issues/218
urlObj.query = urlObj.query || {};
var pathname = decodeURIComponent(urlObj.pathname);
// Backwards compatibility. Options used to be as added as '.' to the
// entry module name. We can safely remove these options.
var entryFile = pathname.replace(/^\//, '').split('.').filter(function(part) {
if (part === 'includeRequire' || part === 'runModule' ||
part === 'bundle' || part === 'map') {
return false;
}
return true;
}).join('.') + '.js';
return {
sourceMapUrl: pathname.replace(/\.bundle$/, '.map'),
entryFile: entryFile,
dev: getBoolOptionFromQuery(urlObj.query, 'dev', true),
minify: getBoolOptionFromQuery(urlObj.query, 'minify'),
runModule: getBoolOptionFromQuery(urlObj.query, 'runModule', true),
inlineSourceMap: getBoolOptionFromQuery(
urlObj.query,
'inlineSourceMap',
false
),
};
}
function getBoolOptionFromQuery(query, opt, defaultVal) {
if (query[opt] == null && defaultVal != null) {
return defaultVal;
}
return query[opt] === 'true' || query[opt] === '1';
}
function handleError(res, error) {
res.writeHead(error.status || 500, {
'Content-Type': 'application/json; charset=UTF-8',
});
if (error.type === 'TransformError' || error.type === 'NotFoundError') {
error.errors = [{
description: error.description,
filename: error.filename,
lineNumber: error.lineNumber,
}];
console.error(error);
res.end(JSON.stringify(error));
} else {
console.error(error.stack || error);
res.end(JSON.stringify({
type: 'InternalError',
message: 'react-packager has encountered an internal error, ' +
'please check your terminal error output for more details',
}));
}
}
|
packages/material-ui-icons/legacy/Battery90Outlined.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z" /><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z" /></React.Fragment>
, 'Battery90Outlined');
|
packages/material-ui-icons/src/ThumbDownOutlined.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm0 12l-4.34 4.34L12 14H3v-2l3-7h9v10zm4-12h4v12h-4z" />
, 'ThumbDownOutlined');
|
client2/src/components/whiteboard/painting.js | gdomorski/CodeOut | import React, { Component } from 'react';
import ReactDOM from 'react-dom'
export default class Painting extends Component {
componentDidMount () {
let canvas = ReactDOM.findDOMNode(this);
let context = canvas.getContext("2d");
let savedImage = new Image();
savedImage.src=this.props.url;
context.drawImage(savedImage,0,0,300,150);
}
render(){
const divStyle = {
'borderStyle': 'solid',
'borderWidth': '0.5px 0.5px 0.5px 0.5px',
'borderColor': 'black',
'backgroundColor': 'white',
}
return (
<canvas style={divStyle} id ={this.props.id}></canvas>
)
}
} |
Scripts/jquery.mobile-1.3.2.js | afandylamusu/storeO | /*!
* jQuery Mobile 1.3.2
* Git HEAD hash: 528cf0e96940644ea644096bfeb913ed920ffaef <> Date: Fri Jul 19 2013 22:17:57 UTC
* http://jquerymobile.com
*
* Copyright 2010, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
// Browser globals
factory( root.jQuery, root, doc );
}
}( this, document, function ( jQuery, window, document, undefined ) {
(function( $ ) {
$.mobile = {};
}( jQuery ));
(function( $, window, undefined ) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.mobile = $.extend($.mobile, {
// Version of the jQuery Mobile Framework
version: "1.3.2",
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Class used for "focus" form element state, from CSS framework
focusClass: "ui-focus",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "fade",
// Set maximum window width for transitions to apply - 'false' for no limit
maxTransitionWidth: false,
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
touchOverflowEnabled: false,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
// For error messages, which theme does the box uses?
pageLoadErrorMessageTheme: "e",
// replace calls to window.history.back with phonegaps navigation helper
// where it is provided on the window object
phonegapNavigationEnabled: false,
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// allows users to opt in to ignoring content by marking a parent element as
// data-ignored
ignoreContentEnabled: false,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
buttonMarkup: {
hoverDelay: 200
},
// define the window and the document objects
window: $( window ),
document: $( document ),
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Place to store various widget extensions
behaviors: {},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function( ypos ) {
if ( $.type( ypos ) !== "number" ) {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout( function() {
window.scrollTo( 0, ypos );
$.mobile.document.trigger( "silentscroll", { x: 0, y: ypos });
}, 20 );
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function( prop ) {
if ( !prop ) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
},
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
getInheritedTheme: function( el, defaultTheme ) {
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body|overlay)-([a-z])\b/,
c, m;
while ( e ) {
c = e.className || "";
if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
},
// TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
//
// Find the closest javascript page element to gather settings data jsperf test
// http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
// possibly naive, but it shows that the parsing overhead for *just* the page selector vs
// the page and dialog selector is negligable. This could probably be speed up by
// doing a similar parent node traversal to the one found in the inherited theme code above
closestPageData: function( $target ) {
return $target
.closest( ':jqmData(role="page"), :jqmData(role="dialog")' )
.data( "mobile-page" );
},
enhanceable: function( $set ) {
return this.haveParents( $set, "enhance" );
},
hijackable: function( $set ) {
return this.haveParents( $set, "ajax" );
},
haveParents: function( $set, attr ) {
if ( !$.mobile.ignoreContentEnabled ) {
return $set;
}
var count = $set.length,
$newSet = $(),
e, $element, excluded;
for ( var i = 0; i < count; i++ ) {
$element = $set.eq( i );
excluded = false;
e = $set[ i ];
while ( e ) {
var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
if ( c === "false" ) {
excluded = true;
break;
}
e = e.parentNode;
}
if ( !excluded ) {
$newSet = $newSet.add( $element );
}
}
return $newSet;
},
getScreenHeight: function() {
// Native innerHeight returns more accurate value for this across platforms,
// jQuery version is here as a normalized fallback for platforms like Symbian
return window.innerHeight || $.mobile.window.height();
}
}, $.mobile );
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function( prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
if ( prop ) {
prop = $.mobile.nsNormalize( prop );
}
// undefined is permitted as an explicit input for the second param
// in this case it returns the value and does not set it to undefined
if( arguments.length < 2 || value === undefined ){
result = this.data( prop );
} else {
result = this.data( prop, value );
}
}
return result;
};
$.jqmData = function( elem, prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.fn.jqmRemoveData = function( prop ) {
return this.removeData( $.mobile.nsNormalize( prop ) );
};
$.jqmRemoveData = function( elem, prop ) {
return $.removeData( elem, $.mobile.nsNormalize( prop ) );
};
$.fn.removeWithDependents = function() {
$.removeWithDependents( this );
};
$.removeWithDependents = function( elem ) {
var $elem = $( elem );
( $elem.jqmData( 'dependents' ) || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function( newDependents ) {
$.addDependents( $( this ), newDependents );
};
$.addDependents = function( elem, newDependents ) {
var dependents = $( elem ).jqmData( 'dependents' ) || $();
$( elem ).jqmData( 'dependents', $.merge( dependents, newDependents ) );
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html element's text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function() {
return $( "<div/>" ).text( $( this ).text() ).html();
};
// fluent helper function for the mobile namespaced equivalent
$.fn.jqmEnhanceable = function() {
return $.mobile.enhanceable( this );
};
$.fn.jqmHijackable = function() {
return $.mobile.hijackable( this );
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function( selector, context, ret, extra ) {
selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
return oldFind.call( this, selector, context, ret, extra );
};
$.extend( $.find, oldFind );
$.find.matches = function( expr, set ) {
return $.find( expr, null, null, set );
};
$.find.matchesSelector = function( node, expr ) {
return $.find( expr, null, null, [ node ] ).length > 0;
};
})( jQuery, this );
/*!
* jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5)
* http://jqueryui.com
*
* Copyright 2010, 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
}
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function() {
$.Widget.prototype._createWidget.apply( this, arguments );
this._trigger( 'init' );
},
_getCreateOptions: function() {
var elem = this.element,
options = {};
$.each( this.options, function( option ) {
var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
return "-" + c.toLowerCase();
})
);
if ( value !== undefined ) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function( target, useKeepNative ) {
this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
},
enhance: function( targets, useKeepNative ) {
var page, keepNative, $widgetElements = $( targets ), self = this;
// if ignoreContentEnabled is set to true the framework should
// only enhance the selected elements when they do NOT have a
// parent with the data-namespace-ignore attribute
$widgetElements = $.mobile.enhanceable( $widgetElements );
if ( useKeepNative && $widgetElements.length ) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
page = $.mobile.closestPageData( $widgetElements );
keepNative = ( page && page.keepNativeSelector()) || "";
$widgetElements = $widgetElements.not( keepNative );
}
$widgetElements[ this.widgetName ]();
},
raise: function( msg ) {
throw "Widget [" + this.widgetName + "]: " + msg;
}
});
})( jQuery );
(function( $, window ) {
// DEPRECATED
// NOTE global mobile object settings
$.extend( $.mobile, {
// DEPRECATED Should the text be visble in the loading message?
loadingMessageTextVisible: undefined,
// DEPRECATED When the text is visible, what theme does the loading box use?
loadingMessageTheme: undefined,
// DEPRECATED default message setting
loadingMessage: undefined,
// DEPRECATED
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
showPageLoadingMsg: function( theme, msgText, textonly ) {
$.mobile.loading( 'show', theme, msgText, textonly );
},
// DEPRECATED
hidePageLoadingMsg: function() {
$.mobile.loading( 'hide' );
},
loading: function() {
this.loaderWidget.loader.apply( this.loaderWidget, arguments );
}
});
// TODO move loader class down into the widget settings
var loaderClass = "ui-loader", $html = $( "html" ), $window = $.mobile.window;
$.widget( "mobile.loader", {
// NOTE if the global config settings are defined they will override these
// options
options: {
// the theme for the loading message
theme: "a",
// whether the text in the loading message is shown
textVisible: false,
// custom html for the inner content of the loading message
html: "",
// the text to be displayed when the popup is shown
text: "loading"
},
defaultHtml: "<div class='" + loaderClass + "'>" +
"<span class='ui-icon ui-icon-loading'></span>" +
"<h1></h1>" +
"</div>",
// For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
fakeFixLoader: function() {
var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
this.element
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
},
// check position of loader to see if it appears to be "fixed" to center
// if not, use abs positioning
checkLoaderPosition: function() {
var offset = this.element.offset(),
scrollTop = $window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) {
this.element.addClass( "ui-loader-fakefix" );
this.fakeFixLoader();
$window
.unbind( "scroll", this.checkLoaderPosition )
.bind( "scroll", $.proxy( this.fakeFixLoader, this ) );
}
},
resetHtml: function() {
this.element.html( $( this.defaultHtml ).html() );
},
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
// TODO sweet jesus we need to break some of this out
show: function( theme, msgText, textonly ) {
var textVisible, message, $header, loadSettings;
this.resetHtml();
// use the prototype options so that people can set them globally at
// mobile init. Consistency, it's what's for dinner
if ( $.type(theme) === "object" ) {
loadSettings = $.extend( {}, this.options, theme );
// prefer object property from the param then the old theme setting
theme = loadSettings.theme || $.mobile.loadingMessageTheme;
} else {
loadSettings = this.options;
// here we prefer the them value passed as a string argument, then
// we prefer the global option because we can't use undefined default
// prototype options, then the prototype option
theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme;
}
// set the message text, prefer the param, then the settings object
// then loading message
message = msgText || $.mobile.loadingMessage || loadSettings.text;
// prepare the dom
$html.addClass( "ui-loading" );
if ( $.mobile.loadingMessage !== false || loadSettings.html ) {
// boolean values require a bit more work :P, supports object properties
// and old settings
if ( $.mobile.loadingMessageTextVisible !== undefined ) {
textVisible = $.mobile.loadingMessageTextVisible;
} else {
textVisible = loadSettings.textVisible;
}
// add the proper css given the options (theme, text, etc)
// Force text visibility if the second argument was supplied, or
// if the text was explicitly set in the object args
this.element.attr("class", loaderClass +
" ui-corner-all ui-body-" + theme +
" ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) +
( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) );
// TODO verify that jquery.fn.html is ok to use in both cases here
// this might be overly defensive in preventing unknowing xss
// if the html attribute is defined on the loading settings, use that
// otherwise use the fallbacks from above
if ( loadSettings.html ) {
this.element.html( loadSettings.html );
} else {
this.element.find( "h1" ).text( message );
}
// attach the loader to the DOM
this.element.appendTo( $.mobile.pageContainer );
// check that the loader is visible
this.checkLoaderPosition();
// on scroll check the loader position
$window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) );
}
},
hide: function() {
$html.removeClass( "ui-loading" );
if ( $.mobile.loadingMessage ) {
this.element.removeClass( "ui-loader-fakefix" );
}
$.mobile.window.unbind( "scroll", this.fakeFixLoader );
$.mobile.window.unbind( "scroll", this.checkLoaderPosition );
}
});
$window.bind( 'pagecontainercreate', function() {
$.mobile.loaderWidget = $.mobile.loaderWidget || $( $.mobile.loader.prototype.defaultHtml ).loader();
});
})(jQuery, this);
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function( $, window, undefined ) {
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || location.href;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function( fn ) {
return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function() {
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function( val ) { return val; },
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function() {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function() {
timeout_id && clearTimeout( timeout_id );
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get( last_hash );
if ( hash !== last_hash ) {
history_set( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
window.attachEvent && !window.addEventListener && !supports_onhashchange && (function() {
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function() {
if ( !iframe ) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one( 'load', function() {
iframe_src || history_set( get_fragment() );
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr( 'src', iframe_src || 'javascript:0' )
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter( 'body' )[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function() {
try {
if ( event.propertyName === 'title' ) {
iframe.document.title = doc.title;
}
} catch(e) {}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function() {
return get_fragment( iframe.location.href );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function( hash, history_hash ) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if ( hash !== history_hash ) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery,this);
(function( $, undefined ) {
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function( doc, undefined ) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( document ));
// $.mobile.media uses matchMedia to return a boolean.
$.mobile.media = function( q ) {
return window.matchMedia( q ).matches;
};
})(jQuery);
(function( $, undefined ) {
var support = {
touch: "ontouchend" in document
};
$.mobile.support = $.mobile.support || {};
$.extend( $.support, support );
$.extend( $.mobile.support, support );
}( jQuery ));
(function( $, undefined ) {
$.extend( $.support, {
orientation: "orientation" in window && "onorientationchange" in window
});
}( jQuery ));
(function( $, undefined ) {
// thx Modernizr
function propExists( prop ) {
var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
for ( var v in props ) {
if ( fbCSS[ props[ v ] ] !== undefined ) {
return true;
}
}
}
var fakeBody = $( "<body>" ).prependTo( "html" ),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
opera = window.opera,
operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
bb = window.blackberry && !propExists( "-webkit-transform" ); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower
function validStyle( prop, value, check_vend ) {
var div = document.createElement( 'div' ),
uc = function( txt ) {
return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 );
},
vend_pref = function( vend ) {
if( vend === "" ) {
return "";
} else {
return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
}
},
check_style = function( vend ) {
var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
uc_vend = uc( vend ),
propStyle = uc_vend + ( uc_vend === "" ? prop : uc( prop ) );
div.setAttribute( "style", vend_prop );
if ( !!div.style[ propStyle ] ) {
ret = true;
}
},
check_vends = check_vend ? check_vend : vendors,
ret;
for( var i = 0; i < check_vends.length; i++ ) {
check_style( check_vends[i] );
}
return !!ret;
}
function transform3dTest() {
var mqProp = "transform-3d",
// Because the `translate3d` test below throws false positives in Android:
ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" );
if( ret ) {
return !!ret;
}
var el = document.createElement( "div" ),
transforms = {
// We’re omitting Opera for the time being; MS uses unprefixed.
'MozTransform':'-moz-transform',
'transform':'transform'
};
fakeBody.append( el );
for ( var t in transforms ) {
if( el.style[ t ] !== undefined ){
el.style[ t ] = 'translate3d( 100px, 1px, 1px )';
ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] );
}
}
return ( !!ret && ret !== "none" );
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $( "head base" ),
fauxEle = null,
href = "",
link, rebase;
if ( !base.length ) {
base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
} else {
href = base.attr( "href" );
}
link = $( "<a href='testurl' />" ).prependTo( fakeBody );
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if ( fauxEle ) {
fauxEle.remove();
}
return rebase.indexOf( fauxBase ) === 0;
}
// Thanks Modernizr
function cssPointerEventsTest() {
var element = document.createElement( 'x' ),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if ( !( 'pointerEvents' in element.style ) ) {
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild( element );
supports = getComputedStyle &&
getComputedStyle( element, '' ).pointerEvents === 'auto';
documentElement.removeChild( element );
return !!supports;
}
function boundingRect() {
var div = document.createElement( "div" );
return typeof div.getBoundingClientRect !== "undefined";
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.extend( $.mobile, { browser: {} } );
$.mobile.browser.oldIE = (function() {
var v = 3,
div = document.createElement( "div" ),
a = div.all || [];
do {
div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->";
} while( a[0] );
return v > 4 ? v : !v;
})();
function fixedPosition() {
var w = window,
ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
ffversion = !!ffmatch && ffmatch[ 1 ],
operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
omversion = !!operammobilematch && operammobilematch[ 1 ];
if(
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) ||
// Opera Mini
( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) ||
( operammobilematch && omversion < 7458 ) ||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) ||
// Firefox Mobile before 6.0 -
( ffversion && ffversion < 6 ) ||
// WebOS less than 3
( "palmGetResource" in window && wkversion && wkversion < 534 ) ||
// MeeGo
( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) {
return false;
}
return true;
}
$.extend( $.support, {
cssTransitions: "WebKitTransitionEvent" in window ||
validStyle( 'transition', 'height 100ms linear', [ "Webkit", "Moz", "" ] ) &&
!$.mobile.browser.oldIE && !opera,
// Note, Chrome for iOS has an extremely quirky implementation of popstate.
// We've chosen to take the shortest path to a bug fix here for issue #5426
// See the following link for information about the regex chosen
// https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent
pushState: "pushState" in history &&
"replaceState" in history &&
// When running inside a FF iframe, calling replaceState causes an error
!( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) &&
( window.navigator.userAgent.search(/CriOS/) === -1 ),
mediaquery: $.mobile.media( "only all" ),
cssPseudoElement: !!propExists( "content" ),
touchOverflow: !!propExists( "overflowScrolling" ),
cssTransform3d: transform3dTest(),
boxShadow: !!propExists( "boxShadow" ) && !bb,
fixedPosition: fixedPosition(),
scrollTop: ("pageXOffset" in window ||
"scrollTop" in document.documentElement ||
"scrollTop" in fakeBody[ 0 ]) && !webos && !operamini,
dynamicBaseTag: baseTagTest(),
cssPointerEvents: cssPointerEventsTest(),
boundingRect: boundingRect()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function() {
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf( "Nokia" ) > -1 &&
( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
ua.indexOf( "AppleWebKit" ) > -1 &&
ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
})();
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
$.mobile.gradeA = function() {
return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null );
};
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if ( nokiaLTE7_3 ) {
$(function() {
$( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
});
}
// For ruling out shadows via css
if ( !$.support.boxShadow ) {
$( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
}
})( jQuery );
(function( $, undefined ) {
var $win = $.mobile.window, self, history;
$.event.special.navigate = self = {
bound: false,
pushStateEnabled: true,
originalEventName: undefined,
// If pushstate support is present and push state support is defined to
// be true on the mobile namespace.
isPushStateEnabled: function() {
return $.support.pushState &&
$.mobile.pushStateEnabled === true &&
this.isHashChangeEnabled();
},
// !! assumes mobile namespace is present
isHashChangeEnabled: function() {
return $.mobile.hashListeningEnabled === true;
},
// TODO a lot of duplication between popstate and hashchange
popstate: function( event ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" ),
state = event.originalEvent.state || {},
href = location.href;
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
if( event.historyState ){
$.extend(state, event.historyState);
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// NOTE we let the current stack unwind because any assignment to
// location.hash will stop the world and run this event handler. By
// doing this we create a similar behavior to hashchange on hash
// assignment
setTimeout(function() {
$win.trigger( newEvent, {
state: state
});
}, 0);
},
hashchange: function( event, data ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" );
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// Trigger the hashchange with state provided by the user
// that altered the hash
$win.trigger( newEvent, {
// Users that want to fully normalize the two events
// will need to do history management down the stack and
// add the state to the event before this binding is fired
// TODO consider allowing for the explicit addition of callbacks
// to be fired before this value is set to avoid event timing issues
state: event.hashchangeState || {}
});
},
// TODO We really only want to set this up once
// but I'm not clear if there's a beter way to achieve
// this with the jQuery special event structure
setup: function( data, namespaces ) {
if( self.bound ) {
return;
}
self.bound = true;
if( self.isPushStateEnabled() ) {
self.originalEventName = "popstate";
$win.bind( "popstate.navigate", self.popstate );
} else if ( self.isHashChangeEnabled() ){
self.originalEventName = "hashchange";
$win.bind( "hashchange.navigate", self.hashchange );
}
}
};
})( jQuery );
(function( $, undefined ) {
var path, documentBase, $base, dialogHashKey = "&ui-state=dialog";
$.mobile.path = path = {
uiStateKey: "&ui-state",
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:[email protected]:8080/mail/inbox
// [3]: http://jblas:[email protected]:8080
// [4]: http:
// [5]: //
// [6]: jblas:[email protected]:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
// Abstraction to address xss (Issue #4787) by removing the authority in
// browsers that auto decode it. All references to location.href should be
// replaced with a call to this method so that it can be dealt with properly here
getLocation: function( url ) {
var uri = url ? this.parseUrl( url ) : location,
hash = this.parseUrl( url || location.href ).hash;
// mimic the browser with an empty string when the hash is empty
hash = hash === "#" ? "" : hash;
// Make sure to parse the url or the location object for the hash because using location.hash
// is autodecoded in firefox, the rest of the url should be from the object (location unless
// we're testing) to avoid the inclusion of the authority
return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
},
parseLocation: function() {
return this.parseUrl( this.getLocation() );
},
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function( url ) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ( $.type( url ) === "object" ) {
return url;
}
var matches = path.urlParseRE.exec( url || "" ) || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function( relPath, absPath ) {
if ( relPath && relPath.charAt( 0 ) === "/" ) {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
var absStack = absPath ? absPath.split( "/" ) : [],
relStack = relPath.split( "/" );
for ( var i = 0; i < relStack.length; i++ ) {
var d = relStack[ i ];
switch ( d ) {
case ".":
break;
case "..":
if ( absStack.length ) {
absStack.pop();
}
break;
default:
absStack.push( d );
break;
}
}
return "/" + absStack.join( "/" );
},
//Returns true if both urls have the same domain.
isSameDomain: function( absUrl1, absUrl2 ) {
return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function( url ) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl( url ).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function( url ) {
return path.parseUrl( url ).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function( relUrl, absUrl ) {
if ( !path.isRelativeUrl( relUrl ) ) {
return relUrl;
}
if ( absUrl === undefined ) {
absUrl = this.documentBase;
}
var relObj = path.parseUrl( relUrl ),
absObj = path.parseUrl( absUrl ),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function( url, params ) {
var u = path.parseUrl( url ),
p = ( typeof params === "object" ) ? $.param( params ) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function( absUrl ) {
var u = path.parseUrl( absUrl );
if ( path.isEmbeddedPage( u ) ) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// and remove otherwise the Data Url won't match the id of the embedded Page.
return u.hash
.split( dialogHashKey )[0]
.replace( /^#/, "" )
.replace( /\?.*$/, "" );
} else if ( path.isSameDomain( u, this.documentBase ) ) {
return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0];
}
return window.decodeURIComponent(absUrl);
},
//get path from current hash, or from a file path
get: function( newPath ) {
if ( newPath === undefined ) {
newPath = path.parseLocation().hash;
}
return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
},
//set location hash to path
set: function( path ) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function( url ) {
return ( /\// ).test( url );
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function( url ) {
return url.replace( this.documentBase.domain, "" );
},
//just return the url without an initial #
stripHash: function( url ) {
return url.replace( /^#/, "" );
},
stripQueryParams: function( url ) {
return url.replace( /\?.*$/, "" );
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function( hash ) {
return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
},
isHashValid: function( hash ) {
return ( /^#[^#]+$/ ).test( hash );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ) {
var u = path.parseUrl( url );
return u.protocol && u.domain !== this.documentUrl.domain ? true : false;
},
hasProtocol: function( url ) {
return ( /^(:?\w+:)/ ).test( url );
},
isEmbeddedPage: function( url ) {
var u = path.parseUrl( url );
//if the path is absolute, then we need to compare the url against
//both the this.documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if ( u.protocol !== "" ) {
return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) );
}
return ( /^#/ ).test( u.href );
},
squash: function( url, resolutionUrl ) {
var state, href, cleanedUrl, search, stateIndex,
isPath = this.isPath( url ),
uri = this.parseUrl( url ),
preservedHash = uri.hash,
uiState = "";
// produce a url against which we can resole the provided path
resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl());
// If the url is anything but a simple string, remove any preceding hash
// eg #foo/bar -> foo/bar
// #foo -> #foo
cleanedUrl = isPath ? path.stripHash( url ) : url;
// If the url is a full url with a hash check if the parsed hash is a path
// if it is, strip the #, and use it otherwise continue without change
cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl;
// Split the UI State keys off the href
stateIndex = cleanedUrl.indexOf( this.uiStateKey );
// store the ui state keys for use
if( stateIndex > -1 ){
uiState = cleanedUrl.slice( stateIndex );
cleanedUrl = cleanedUrl.slice( 0, stateIndex );
}
// make the cleanedUrl absolute relative to the resolution url
href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl );
// grab the search from the resolved url since parsing from
// the passed url may not yield the correct result
search = this.parseUrl( href ).search;
// TODO all this crap is terrible, clean it up
if ( isPath ) {
// reject the hash if it's a path or it's just a dialog key
if( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) {
preservedHash = "";
}
// Append the UI State keys where it exists and it's been removed
// from the url
if( uiState && preservedHash.indexOf( this.uiStateKey ) === -1){
preservedHash += uiState;
}
// make sure that pound is on the front of the hash
if( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ){
preservedHash = "#" + preservedHash;
}
// reconstruct each of the pieces with the new search string and hash
href = path.parseUrl( href );
href = href.protocol + "//" + href.host + href.pathname + search + preservedHash;
} else {
href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState;
}
return href;
},
isPreservableHash: function( hash ) {
return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0;
}
};
path.documentUrl = path.parseLocation();
$base = $( "head" ).find( "base" );
path.documentBase = $base.length ?
path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) :
path.documentUrl;
path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash);
//return the original document url
path.getDocumentUrl = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href;
};
//return the original document base url
path.getDocumentBase = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href;
};
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path;
$.mobile.History = function( stack, index ) {
this.stack = stack || [];
this.activeIndex = index || 0;
};
$.extend($.mobile.History.prototype, {
getActive: function() {
return this.stack[ this.activeIndex ];
},
getLast: function() {
return this.stack[ this.previousIndex ];
},
getNext: function() {
return this.stack[ this.activeIndex + 1 ];
},
getPrev: function() {
return this.stack[ this.activeIndex - 1 ];
},
// addNew is used whenever a new page is added
add: function( url, data ){
data = data || {};
//if there's forward history, wipe it
if ( this.getNext() ) {
this.clearForward();
}
// if the hash is included in the data make sure the shape
// is consistent for comparison
if( data.hash && data.hash.indexOf( "#" ) === -1) {
data.hash = "#" + data.hash;
}
data.url = url;
this.stack.push( data );
this.activeIndex = this.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function() {
this.stack = this.stack.slice( 0, this.activeIndex + 1 );
},
find: function( url, stack, earlyReturn ) {
stack = stack || this.stack;
var entry, i, length = stack.length, index;
for ( i = 0; i < length; i++ ) {
entry = stack[i];
if ( decodeURIComponent(url) === decodeURIComponent(entry.url) ||
decodeURIComponent(url) === decodeURIComponent(entry.hash) ) {
index = i;
if( earlyReturn ) {
return index;
}
}
}
return index;
},
closest: function( url ) {
var closest, a = this.activeIndex;
// First, take the slice of the history stack before the current index and search
// for a url match. If one is found, we'll avoid avoid looking through forward history
// NOTE the preference for backward history movement is driven by the fact that
// most mobile browsers only have a dedicated back button, and users rarely use
// the forward button in desktop browser anyhow
closest = this.find( url, this.stack.slice(0, a) );
// If nothing was found in backward history check forward. The `true`
// value passed as the third parameter causes the find method to break
// on the first match in the forward history slice. The starting index
// of the slice must then be added to the result to get the element index
// in the original history stack :( :(
//
// TODO this is hyper confusing and should be cleaned up (ugh so bad)
if( closest === undefined ) {
closest = this.find( url, this.stack.slice(a), true );
closest = closest === undefined ? closest : closest + a;
}
return closest;
},
direct: function( opts ) {
var newActiveIndex = this.closest( opts.url ), a = this.activeIndex;
// save new page index, null check to prevent falsey 0 result
// record the previous index for reference
if( newActiveIndex !== undefined ) {
this.activeIndex = newActiveIndex;
this.previousIndex = a;
}
// invoke callbacks where appropriate
//
// TODO this is also convoluted and confusing
if ( newActiveIndex < a ) {
( opts.present || opts.back || $.noop )( this.getActive(), 'back' );
} else if ( newActiveIndex > a ) {
( opts.present || opts.forward || $.noop )( this.getActive(), 'forward' );
} else if ( newActiveIndex === undefined && opts.missing ){
opts.missing( this.getActive() );
}
}
});
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path,
initialHref = location.href;
$.mobile.Navigator = function( history ) {
this.history = history;
this.ignoreInitialHashChange = true;
$.mobile.window.bind({
"popstate.history": $.proxy( this.popstate, this ),
"hashchange.history": $.proxy( this.hashchange, this )
});
};
$.extend($.mobile.Navigator.prototype, {
squash: function( url, data ) {
var state, href, hash = path.isPath(url) ? path.stripHash(url) : url;
href = path.squash( url );
// make sure to provide this information when it isn't explicitly set in the
// data object that was passed to the squash method
state = $.extend({
hash: hash,
url: href
}, data);
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where $.mobile.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
window.history.replaceState( state, state.title || document.title, href );
return state;
},
hash: function( url, href ) {
var parsed, loc, hash;
// Grab the hash for recording. If the passed url is a path
// we used the parsed version of the squashed url to reconstruct,
// otherwise we assume it's a hash and store it directly
parsed = path.parseUrl( url );
loc = path.parseLocation();
if( loc.pathname + loc.search === parsed.pathname + parsed.search ) {
// If the pathname and search of the passed url is identical to the current loc
// then we must use the hash. Otherwise there will be no event
// eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz"
hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search;
} else if ( path.isPath(url) ) {
var resolved = path.parseUrl( href );
// If the passed url is a path, make it domain relative and remove any trailing hash
hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : "");
} else {
hash = url;
}
return hash;
},
// TODO reconsider name
go: function( url, data, noEvents ) {
var state, href, hash, popstateEvent,
isPopStateEvent = $.event.special.navigate.isPushStateEnabled();
// Get the url as it would look squashed on to the current resolution url
href = path.squash( url );
// sort out what the hash sould be from the url
hash = this.hash( url, href );
// Here we prevent the next hash change or popstate event from doing any
// history management. In the case of hashchange we don't swallow it
// if there will be no hashchange fired (since that won't reset the value)
// and will swallow the following hashchange
if( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) {
this.preventNextHashChange = noEvents;
}
// IMPORTANT in the case where popstate is supported the event will be triggered
// directly, stopping further execution - ie, interupting the flow of this
// method call to fire bindings at this expression. Below the navigate method
// there is a binding to catch this event and stop its propagation.
//
// We then trigger a new popstate event on the window with a null state
// so that the navigate events can conclude their work properly
//
// if the url is a path we want to preserve the query params that are available on
// the current url.
this.preventHashAssignPopState = true;
window.location.hash = hash;
// If popstate is enabled and the browser triggers `popstate` events when the hash
// is set (this often happens immediately in browsers like Chrome), then the
// this flag will be set to false already. If it's a browser that does not trigger
// a `popstate` on hash assignement or `replaceState` then we need avoid the branch
// that swallows the event created by the popstate generated by the hash assignment
// At the time of this writing this happens with Opera 12 and some version of IE
this.preventHashAssignPopState = false;
state = $.extend({
url: href,
hash: hash,
title: document.title
}, data);
if( isPopStateEvent ) {
popstateEvent = new $.Event( "popstate" );
popstateEvent.originalEvent = {
type: "popstate",
state: null
};
this.squash( url, state );
// Trigger a new faux popstate event to replace the one that we
// caught that was triggered by the hash setting above.
if( !noEvents ) {
this.ignorePopState = true;
$.mobile.window.trigger( popstateEvent );
}
}
// record the history entry so that the information can be included
// in hashchange event driven navigate events in a similar fashion to
// the state that's provided by popstate
this.history.add( state.url, state );
},
// This binding is intended to catch the popstate events that are fired
// when execution of the `$.navigate` method stops at window.location.hash = url;
// and completely prevent them from propagating. The popstate event will then be
// retriggered after execution resumes
//
// TODO grab the original event here and use it for the synthetic event in the
// second half of the navigate execution that will follow this binding
popstate: function( event ) {
var active, hash, state, closestIndex;
// Partly to support our test suite which manually alters the support
// value to test hashchange. Partly to prevent all around weirdness
if( !$.event.special.navigate.isPushStateEnabled() ){
return;
}
// If this is the popstate triggered by the actual alteration of the hash
// prevent it completely. History is tracked manually
if( this.preventHashAssignPopState ) {
this.preventHashAssignPopState = false;
event.stopImmediatePropagation();
return;
}
// if this is the popstate triggered after the `replaceState` call in the go
// method, then simply ignore it. The history entry has already been captured
if( this.ignorePopState ) {
this.ignorePopState = false;
return;
}
// If there is no state, and the history stack length is one were
// probably getting the page load popstate fired by browsers like chrome
// avoid it and set the one time flag to false.
// TODO: Do we really need all these conditions? Comparing location hrefs
// should be sufficient.
if( !event.originalEvent.state &&
this.history.stack.length === 1 &&
this.ignoreInitialHashChange ) {
this.ignoreInitialHashChange = false;
if ( location.href === initialHref ) {
event.preventDefault();
return;
}
}
// account for direct manipulation of the hash. That is, we will receive a popstate
// when the hash is changed by assignment, and it won't have a state associated. We
// then need to squash the hash. See below for handling of hash assignment that
// matches an existing history entry
// TODO it might be better to only add to the history stack
// when the hash is adjacent to the active history entry
hash = path.parseLocation().hash;
if( !event.originalEvent.state && hash ) {
// squash the hash that's been assigned on the URL with replaceState
// also grab the resulting state object for storage
state = this.squash( hash );
// record the new hash as an additional history entry
// to match the browser's treatment of hash assignment
this.history.add( state.url, state );
// pass the newly created state information
// along with the event
event.historyState = state;
// do not alter history, we've added a new history entry
// so we know where we are
return;
}
// If all else fails this is a popstate that comes from the back or forward buttons
// make sure to set the state of our history stack properly, and record the directionality
this.history.direct({
url: (event.originalEvent.state || {}).url || hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.historyState = $.extend({}, historyEntry);
event.historyState.direction = direction;
}
});
},
// NOTE must bind before `navigate` special event hashchange binding otherwise the
// navigation data won't be attached to the hashchange event in time for those
// bindings to attach it to the `navigate` special event
// TODO add a check here that `hashchange.navigate` is bound already otherwise it's
// broken (exception?)
hashchange: function( event ) {
var history, hash;
// If hashchange listening is explicitly disabled or pushstate is supported
// avoid making use of the hashchange handler.
if(!$.event.special.navigate.isHashChangeEnabled() ||
$.event.special.navigate.isPushStateEnabled() ) {
return;
}
// On occasion explicitly want to prevent the next hash from propogating because we only
// with to alter the url to represent the new state do so here
if( this.preventNextHashChange ){
this.preventNextHashChange = false;
event.stopImmediatePropagation();
return;
}
history = this.history;
hash = path.parseLocation().hash;
// If this is a hashchange caused by the back or forward button
// make sure to set the state of our history stack properly
this.history.direct({
url: hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.hashchangeState = $.extend({}, historyEntry);
event.hashchangeState.direction = direction;
},
// When we don't find a hash in our history clearly we're aiming to go there
// record the entry as new for future traversal
//
// NOTE it's not entirely clear that this is the right thing to do given that we
// can't know the users intention. It might be better to explicitly _not_
// support location.hash assignment in preference to $.navigate calls
// TODO first arg to add should be the href, but it causes issues in identifying
// embeded pages
missing: function() {
history.add( hash, {
hash: hash,
title: document.title
});
}
});
}
});
})( jQuery );
(function( $, undefined ) {
// TODO consider queueing navigation activity until previous activities have completed
// so that end users don't have to think about it. Punting for now
// TODO !! move the event bindings into callbacks on the navigate event
$.mobile.navigate = function( url, data, noEvents ) {
$.mobile.navigate.navigator.go( url, data, noEvents );
};
// expose the history on the navigate method in anticipation of full integration with
// existing navigation functionalty that is tightly coupled to the history information
$.mobile.navigate.history = new $.mobile.History();
// instantiate an instance of the navigator for use within the $.navigate method
$.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history );
var loc = $.mobile.path.parseLocation();
$.mobile.navigate.history.add( loc.href, {hash: loc.hash} );
})( jQuery );
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function( $, window, document, undefined ) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
mouseEventProps = $.event.props.concat( mouseHookProps ),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $( document ),
nextTouchID = 1,
lastTouchID = 0, threshold;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent( event ) {
while ( event && typeof event.originalEvent !== "undefined" ) {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent( event, eventType ) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j, len;
event = $.Event( event );
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if ( t.search( /^(mouse|click)/ ) > -1 ) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( oe ) {
for ( i = props.length, prop; i; ) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) {
event.which = 1;
}
if ( t.search(/^touch/) !== -1 ) {
ne = getNativeEvent( oe );
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );
if ( touch ) {
for ( j = 0, len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags( element ) {
var flags = {},
b, k;
while ( element ) {
b = $.data( element, dataPropertyName );
for ( k in b ) {
if ( b[ k ] ) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding( element, eventType ) {
var b;
while ( element ) {
b = $.data( element, dataPropertyName );
if ( b && ( !eventType || b[ eventType ] ) ) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout( function() {
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration );
}
function clearResetTimer() {
if ( resetTimerID ) {
clearTimeout( resetTimerID );
resetTimerID = 0;
}
}
function triggerVirtualEvent( eventType, event, flags ) {
var ve;
if ( ( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
ve = createVirtualEvent( event, eventType );
$( event.target).trigger( ve );
}
return ve;
}
function mouseEventCallback( event ) {
var touchID = $.data( event.target, touchTargetPropertyName );
if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) {
var ve = triggerVirtualEvent( "v" + event.type, event );
if ( ve ) {
if ( ve.isDefaultPrevented() ) {
event.preventDefault();
}
if ( ve.isPropagationStopped() ) {
event.stopPropagation();
}
if ( ve.isImmediatePropagationStopped() ) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart( event ) {
var touches = getNativeEvent( event ).touches,
target, flags;
if ( touches && touches.length === 1 ) {
target = event.target;
flags = getVirtualBindingFlags( target );
if ( flags.hasVirtualBinding ) {
lastTouchID = nextTouchID++;
$.data( target, touchTargetPropertyName, lastTouchID );
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent( event ).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent( "vmouseover", event, flags );
triggerVirtualEvent( "vmousedown", event, flags );
}
}
}
function handleScroll( event ) {
if ( blockTouchTriggers ) {
return;
}
if ( !didScroll ) {
triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
}
didScroll = true;
startResetTimer();
}
function handleTouchMove( event ) {
if ( blockTouchTriggers ) {
return;
}
var t = getNativeEvent( event ).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold,
flags = getVirtualBindingFlags( event.target );
didScroll = didScroll ||
( Math.abs( t.pageX - startX ) > moveThreshold ||
Math.abs( t.pageY - startY ) > moveThreshold );
if ( didScroll && !didCancel ) {
triggerVirtualEvent( "vmousecancel", event, flags );
}
triggerVirtualEvent( "vmousemove", event, flags );
startResetTimer();
}
function handleTouchEnd( event ) {
if ( blockTouchTriggers ) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags( event.target ),
t;
triggerVirtualEvent( "vmouseup", event, flags );
if ( !didScroll ) {
var ve = triggerVirtualEvent( "vclick", event, flags );
if ( ve && ve.isDefaultPrevented() ) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent( event ).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent( "vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings( ele ) {
var bindings = $.data( ele, dataPropertyName ),
k;
if ( bindings ) {
for ( k in bindings ) {
if ( bindings[ k ] ) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {}
function getSpecialEventObject( eventType ) {
var realType = eventType.substr( 1 );
return {
setup: function( data, namespace ) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if ( !hasVirtualBindings( this ) ) {
$.data( this, dataPropertyName, {} );
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data( this, dataPropertyName );
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if ( activeDocHandlers[ eventType ] === 1 ) {
$document.bind( realType, mouseEventCallback );
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$( this ).bind( realType, dummyMouseHandler );
// For now, if event capture is not supported, we rely on mouse handlers.
if ( eventCaptureSupported ) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if ( activeDocHandlers[ "touchstart" ] === 1 ) {
$document.bind( "touchstart", handleTouchStart )
.bind( "touchend", handleTouchEnd )
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind( "touchmove", handleTouchMove )
.bind( "scroll", handleScroll );
}
}
},
teardown: function( data, namespace ) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if ( !activeDocHandlers[ eventType ] ) {
$document.unbind( realType, mouseEventCallback );
}
if ( eventCaptureSupported ) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if ( !activeDocHandlers[ "touchstart" ] ) {
$document.unbind( "touchstart", handleTouchStart )
.unbind( "touchmove", handleTouchMove )
.unbind( "touchend", handleTouchEnd )
.unbind( "scroll", handleScroll );
}
}
var $this = $( this ),
bindings = $.data( this, dataPropertyName );
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if ( bindings ) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind( realType, dummyMouseHandler );
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if ( !hasVirtualBindings( this ) ) {
$this.removeData( dataPropertyName );
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for ( var i = 0; i < virtualEventNames.length; i++ ) {
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
document.addEventListener( "click", function( e ) {
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if ( cnt ) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while ( ele ) {
for ( i = 0; i < cnt; i++ ) {
o = clickBlockList[ i ];
touchID = 0;
if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
$.data( ele, touchTargetPropertyName ) === o.touchID ) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})( jQuery, window, document );
(function( $, window, undefined ) {
var $document = $( document );
// add new event shortcuts
$.each( ( "touchstart touchmove touchend " +
"tap taphold " +
"swipe swipeleft swiperight " +
"scrollstart scrollstop" ).split( " " ), function( i, name ) {
$.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ name ] = true;
}
});
var supportTouch = $.mobile.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.dispatch.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout( function() {
trigger( event, false );
}, 50 );
});
}
};
// also handles taphold
$.event.special.tap = {
tapholdThreshold: 750,
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( "vmousedown", function( event ) {
if ( event.which && event.which !== 1 ) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout( timer );
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind( "vclick", clickHandler )
.unbind( "vmouseup", clearTapTimer );
$document.unbind( "vmousecancel", clearTapHandlers );
}
function clickHandler( event ) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if ( origTarget === event.target ) {
triggerCustomEvent( thisObject, "tap", event );
}
}
$this.bind( "vmouseup", clearTapTimer )
.bind( "vclick", clickHandler );
$document.bind( "vmousecancel", clearTapHandlers );
timer = setTimeout( function() {
triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
}, $.event.special.tap.tapholdThreshold );
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
start: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
};
},
stop: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
},
handleSwipe: function( start, stop ) {
if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
start.origin.trigger( "swipe" )
.trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
}
},
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( touchStartEvent, function( event ) {
var start = $.event.special.swipe.start( event ),
stop;
function moveHandler( event ) {
if ( !start ) {
return;
}
stop = $.event.special.swipe.stop( event );
// prevent scrolling
if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
event.preventDefault();
}
}
$this.bind( touchMoveEvent, moveHandler )
.one( touchStopEvent, function() {
$this.unbind( touchMoveEvent, moveHandler );
if ( start && stop ) {
$.event.special.swipe.handleSwipe( start, stop );
}
start = stop = undefined;
});
});
}
};
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function( event, sourceEvent ) {
$.event.special[ event ] = {
setup: function() {
$( this ).bind( sourceEvent, $.noop );
}
};
});
})( jQuery, this );
// throttled resize event
(function( $ ) {
$.event.special.throttledresize = {
setup: function() {
$( this ).bind( "resize", handler );
},
teardown: function() {
$( this ).unbind( "resize", handler );
}
};
var throttle = 250,
handler = function() {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if ( diff >= throttle ) {
lastCall = curr;
$( this ).trigger( "throttledresize" );
} else {
if ( heldCall ) {
clearTimeout( heldCall );
}
// Promise a held call will still execute
heldCall = setTimeout( handler, throttle - diff );
}
},
lastCall = 0,
heldCall,
curr,
diff;
})( jQuery );
(function( $, window ) {
var win = $( window ),
event_name = "orientationchange",
special_event,
get_orientation,
last_orientation,
initial_orientation_is_landscape,
initial_orientation_is_default,
portrait_map = { "0": true, "180": true };
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if ( $.support.orientation ) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || win.width(),
wh = window.innerHeight || win.height(),
landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[ window.orientation ];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
portrait_map = { "-90": true, "90": true };
}
}
$.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind( "throttledresize", handler );
},
teardown: function() {
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind( "throttledresize", handler );
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function( event ) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply( this, arguments );
};
}
});
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if ( orientation !== last_orientation ) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger( event_name );
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function() {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ( $.support.orientation ) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[ window.orientation ];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
$.fn[ event_name ] = function( fn ) {
return fn ? this.bind( event_name, fn ) : this.trigger( event_name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ event_name ] = true;
}
}( jQuery, this ));
(function( $, undefined ) {
$.widget( "mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function() {
// if false is returned by the callbacks do not create the page
if ( this._trigger( "beforecreate" ) === false ) {
return false;
}
this.element
.attr( "tabindex", "0" )
.addClass( "ui-page ui-body-" + this.options.theme );
this._on( this.element, {
pagebeforehide: "removeContainerBackground",
pagebeforeshow: "_handlePageBeforeShow"
});
},
_handlePageBeforeShow: function( e ) {
this.setContainerBackground();
},
removeContainerBackground: function() {
$.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
},
// set the page container background to the page theme
setContainerBackground: function( theme ) {
if ( this.options.theme ) {
$.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
}
},
keepNativeSelector: function() {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim( options.keepNative );
if ( keepNativeDefined && options.keepNative !== options.keepNativeDefault ) {
return [options.keepNative, options.keepNativeDefault].join( ", " );
}
return options.keepNativeDefault;
}
});
})( jQuery );
(function( $, window, undefined ) {
var createHandler = function( sequential ) {
// Default to sequential
if ( sequential === undefined ) {
sequential = true;
}
return function( name, reverse, $to, $from ) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
active = $.mobile.urlHistory.getActive(),
toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
screenHeight = $.mobile.getScreenHeight(),
maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
toPreClass = " ui-page-pre-in",
toggleViewportClass = function() {
$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
},
scrollPage = function() {
// By using scrollTo instead of silentScroll, we can keep things better in order
// Just to be precautios, disable scrollstart listening like silentScroll would
$.event.special.scrollstart.enabled = false;
window.scrollTo( 0, toScroll );
// reenable scrollstart listening like silentScroll would
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
cleanFrom = function() {
$from
.removeClass( $.mobile.activePageClass + " out in reverse " + name )
.height( "" );
},
startOut = function() {
// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
if ( !sequential ) {
doneOut();
}
else {
$from.animationComplete( doneOut );
}
// Set the from page's height and start it transitioning out
// Note: setting an explicit height helps eliminate tiling in the transitions
$from
.height( screenHeight + $.mobile.window.scrollTop() )
.addClass( name + " out" + reverseClass );
},
doneOut = function() {
if ( $from && sequential ) {
cleanFrom();
}
startIn();
},
startIn = function() {
// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
$to.css( "z-index", -10 );
$to.addClass( $.mobile.activePageClass + toPreClass );
// Send focus to page as it is now display: block
$.mobile.focusPage( $to );
// Set to page height
$to.height( screenHeight + toScroll );
scrollPage();
// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
$to.css( "z-index", "" );
if ( !none ) {
$to.animationComplete( doneIn );
}
$to
.removeClass( toPreClass )
.addClass( name + " in" + reverseClass );
if ( none ) {
doneIn();
}
},
doneIn = function() {
if ( !sequential ) {
if ( $from ) {
cleanFrom();
}
}
$to
.removeClass( "out in reverse " + name )
.height( "" );
toggleViewportClass();
// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
// This ensures we jump to that spot after the fact, if we aren't there already.
if ( $.mobile.window.scrollTop() !== toScroll ) {
scrollPage();
}
deferred.resolve( name, reverse, $to, $from, true );
};
toggleViewportClass();
if ( $from && !none ) {
startOut();
}
else {
doneOut();
}
return deferred.promise();
};
};
// generate the handlers from the above
var sequentialHandler = createHandler(),
simultaneousHandler = createHandler( false ),
defaultGetMaxScrollForTransition = function() {
return $.mobile.getScreenHeight() * 3;
};
// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
"default": $.mobile.defaultTransitionHandler,
"sequential": sequentialHandler,
"simultaneous": simultaneousHandler
};
$.mobile.transitionFallbacks = {};
// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function( transition ) {
if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
transition = $.mobile.transitionFallbacks[ transition ];
}
return transition;
};
// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})( jQuery, this );
(function( $, undefined ) {
//define vars for interal use
var $window = $.mobile.window,
$html = $( 'html' ),
$head = $( 'head' ),
// NOTE: path extensions dependent on core attributes. Moved here to remove deps from
// $.mobile.path definition
path = $.extend($.mobile.path, {
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function( url ) {
// We only deal with absolute paths.
var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
},
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
return $.mobile.allowCrossDomainPages &&
docUrl.protocol === "file:" &&
reqUrl.search( /^https?:/ ) !== -1;
}
}),
// used to track last vclicked element to make sure its value is added to form data
$lastVClicked = null,
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
// resolved on domready
domreadyDeferred = $.Deferred(),
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = $.mobile.navigate.history,
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children( "base" ),
//tuck away the original document URL minus any fragment.
documentUrl = path.documentUrl,
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = path.documentBase,
//cache the comparison once.
documentBaseDiffers = path.documentBaseDiffers,
getScreenHeight = $.mobile.getScreenHeight;
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ) {
href = path.parseUrl(href).hrefNoHash;
base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
},
//set the generated BASE element's href attribute to a new page's base path
reset: function() {
base.element.attr( "href", documentBase.hrefNoSearch );
}
} : undefined;
//return the original document url
$.mobile.getDocumentUrl = path.getDocumentUrl;
//return the original document base url
$.mobile.getDocumentBase = path.getDocumentBase;
/* internal utility functions */
// NOTE Issue #4950 Android phonegap doesn't navigate back properly
// when a full page refresh has taken place. It appears that hashchange
// and replacestate history alterations work fine but we need to support
// both forms of history traversal in our code that uses backward history
// movement
$.mobile.back = function() {
var nav = window.navigator;
// if the setting is on and the navigator object is
// available use the phonegap navigation capability
if( this.phonegapNavigationEnabled &&
nav &&
nav.app &&
nav.app.backHistory ){
nav.app.backHistory();
} else {
window.history.back();
}
};
//direct focus to the page title, or otherwise first focusable element
$.mobile.focusPage = function ( page ) {
var autofocus = page.find( "[autofocus]" ),
pageTitle = page.find( ".ui-title:eq(0)" );
if ( autofocus.length ) {
autofocus.focus();
return;
}
if ( pageTitle.length ) {
pageTitle.focus();
} else{
page.focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ) {
if ( !!$activeClickedLink && ( !$activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) {
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if ( pageTransitionQueue.length > 0 ) {
$.mobile.changePage.apply( null, pageTransitionQueue.pop() );
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
setLastScroll, delayedSetLastScroll;
setLastScroll = function() {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if ( !setLastScrollEnabled ) {
return;
}
var active = $.mobile.urlHistory.getActive();
if ( active ) {
var lastScroll = $window.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function() {
setTimeout( setLastScroll, 100 );
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one( "pagecontainercreate", function() {
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind( "pagechange", function() {
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
$window.unbind( "scrollstop", delayedSetLastScroll );
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
$window.bind( "scrollstop", delayedSetLastScroll );
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
$window.bind( "scrollstop", delayedSetLastScroll );
// No-op implementation of transition degradation
$.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) {
return transition;
};
//function for transitioning between two existing pages
function transitionPages( toPage, fromPage, transition, reverse ) {
if ( fromPage ) {
//trigger before show/hide events
fromPage.data( "mobile-page" )._trigger( "beforehide", null, { nextPage: toPage } );
}
toPage.data( "mobile-page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
//clear page loader
$.mobile.hidePageLoadingMsg();
transition = $.mobile._maybeDegradeTransition( transition );
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
promise = th( transition, reverse, toPage, fromPage );
promise.done(function() {
//trigger show/hide events
if ( fromPage ) {
fromPage.data( "mobile-page" )._trigger( "hide", null, { nextPage: toPage } );
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data( "mobile-page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
$.mobile.resetActivePageHeight = function resetActivePageHeight( height ) {
var aPage = $( "." + $.mobile.activePageClass ),
aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
height = ( typeof height === "number" )? height : getScreenHeight();
aPage.css( "min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
};
//shared page enhancements
function enhancePage( $page, role ) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if ( role ) {
$page.attr( "data-" + $.mobile.ns + "role", role );
}
//run page plugin
$page.page();
}
// determine the current base url
function findBaseWithDefault() {
var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
return closestBase || documentBase.hrefNoHash;
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function( callback ) {
if ( $.support.cssTransitions ) {
return $( this ).one( 'webkitAnimationEnd animationend', callback );
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout( callback, 0 );
return $( this );
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
$.mobile._bindPageRemove = function() {
var page = $( this );
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if ( !page.data( "mobile-page" ).options.domCache &&
page.is( ":jqmData(external-page='true')" ) ) {
page.bind( 'pagehide.remove', function( e ) {
var $this = $( this ),
prEvent = new $.Event( "pageremove" );
$this.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function( url, options ) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if ( settings.data && settings.type === "get" ) {
absUrl = path.addSearchParams( absUrl, settings.data );
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if ( settings.data && settings.type === "post" ) {
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath( absUrl ),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl( absUrl );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
// NOTE do _not_ use the :jqmData psuedo selector because parenthesis
// are a valid url char and it breaks on the first occurence
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
page = settings.pageContainer.children( "#" + dataUrl )
.attr( "data-" + $.mobile.ns + "url", dataUrl )
.jqmData( "url", dataUrl );
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if ( page.length === 0 ) {
if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ( $.mobile.firstPage.parent().length ) {
page = $( $.mobile.firstPage );
}
} else if ( path.isEmbeddedPage( fileUrl ) ) {
deferred.reject( absUrl, options );
return deferred.promise();
}
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if ( page.length ) {
if ( !settings.reloadPage ) {
enhancePage( page, settings.role );
deferred.resolve( absUrl, options, page );
//if we are reloading the page make sure we update the base if its not a prefetch
if( base && !options.prefetch ){
base.set(url);
}
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event( "pagebeforeload" ),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger( pblEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pblEvent.isDefaultPrevented() ) {
return deferred.promise();
}
if ( settings.showLoadMsg ) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function() {
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay ),
// Shared logic for clearing timeout and removing message.
hideMsg = function() {
// Stop message show timer
clearTimeout( loadMsgDelay );
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
// Reset base to the default document base.
// only reset if we are not prefetching
if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" ) ) {
base.reset();
}
if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
deferred.reject( absUrl, options );
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
contentType: settings.contentType,
dataType: "html",
success: function( html, textStatus, xhr ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $( "<div></div>" ),
//page title regexp
newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if ( pageElemRegex.test( html ) &&
RegExp.$1 &&
dataUrlRegex.test( RegExp.$1 ) &&
RegExp.$1 ) {
url = fileUrl = path.getFilePath( $( "<div>" + RegExp.$1 + "</div>" ).text() );
}
//dont update the base tag if we are prefetching
if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" )) {
base.set( fileUrl );
}
//workaround to allow scripts to execute when included in page divs
all.get( 0 ).innerHTML = html;
page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
//if page elem couldn't be found, create one and insert the body element's contents
if ( !page.length ) {
page = $( "<div data-" + $.mobile.ns + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" );
}
if ( newPageTitle && !page.jqmData( "title" ) ) {
if ( ~newPageTitle.indexOf( "&" ) ) {
newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
}
page.jqmData( "title", newPageTitle );
}
//rewrite src and href attrs to use a base url
if ( !$.support.dynamicBaseTag ) {
var newPath = path.get( fileUrl );
page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
var thisAttr = $( this ).is( '[href]' ) ? 'href' :
$( this ).is( '[src]' ) ? 'src' : 'action',
thisUrl = $( this ).attr( thisAttr );
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
$( this ).attr( thisAttr, newPath + thisUrl );
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
.attr( "data-" + $.mobile.ns + "external-page", true )
.appendTo( settings.pageContainer );
// wait for page creation to leverage options defined on widget
page.one( 'pagecreate', $.mobile._bindPageRemove );
enhancePage( page, settings.role );
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
}
// Remove loading message.
if ( settings.showLoadMsg ) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger( "pageload", triggerData );
deferred.resolve( absUrl, options, page, dupCachedPage );
},
error: function( xhr, textStatus, errorThrown ) {
//set base back to current path
if ( base ) {
base.set( path.get() );
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event( "pageloadfailed" );
// Let listeners know the page load failed.
settings.pageContainer.trigger( plfEvent, triggerData );
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if ( plfEvent.isDefaultPrevented() ) {
return;
}
// Remove loading message.
if ( settings.showLoadMsg ) {
// Remove loading message.
hideMsg();
// show error message
$.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
// hide after delay
setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
}
deferred.reject( absUrl, options );
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function( toPage, options ) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if ( isPageTransitioning ) {
pageTransitionQueue.unshift( arguments );
return;
}
var settings = $.extend( {}, $.mobile.changePage.defaults, options ), isToPageString;
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
isToPageString = (typeof toPage === "string");
var mpc = settings.pageContainer,
pbcEvent = new $.Event( "pagebeforechange" ),
triggerData = { toPage: toPage, options: settings };
// NOTE: preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
if ( isToPageString ) {
// if the toPage is a string simply convert it
triggerData.absUrl = path.makeUrlAbsolute( toPage, findBaseWithDefault() );
} else {
// if the toPage is a jQuery object grab the absolute url stored
// in the loadPage callback where it exists
triggerData.absUrl = toPage.data( 'absUrl' );
}
// Let listeners know we're about to change the current page.
mpc.trigger( pbcEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pbcEvent.isDefaultPrevented() ) {
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
//
// We also need to re-evaluate whether it is a string, because an object can
// also be replaced by a string
toPage = triggerData.toPage;
isToPageString = (typeof toPage === "string");
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if ( isToPageString ) {
// preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
settings.target = toPage;
$.mobile.loadPage( toPage, settings )
.done(function( url, options, newPage, dupCachedPage ) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
// store the original absolute url so that it can be provided
// to events in the triggerData of the subsequent changePage call
newPage.data( 'absUrl', triggerData.absUrl );
$.mobile.changePage( newPage, options );
})
.fail(function( url, options ) {
//clear out the active button state
removeActiveLinkClass( true );
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger( "pagechangefailed", triggerData );
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath( url ),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
isPageTransitioning = false;
mpc.trigger( "pagechange", triggerData );
// Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
if ( settings.fromHashChange ) {
urlHistory.direct({ url: url });
}
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage( toPage, settings.role );
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if ( settings.fromHashChange ) {
historyDir = options.direction === "back" ? -1 : 1;
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a delegate() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body' ) {
$( document.activeElement ).blur();
} else {
$( "input:focus, textarea:focus, select:focus" ).blur();
}
} catch( e ) {}
// Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
var alreadyThere = false;
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if ( isDialog && active ) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
// If we are at a place in history that once belonged to a dialog, reuse
// this state without adding to urlHistory and without modifying the hash.
// However, if a dialog is already displayed at this point, and we're
// about to display another dialog, then we must add another hash and
// history entry on top so that one may navigate back to the original dialog
if ( active.url &&
active.url.indexOf( dialogHashKey ) > -1 &&
$.mobile.activePage &&
!$.mobile.activePage.is( ".ui-dialog" ) &&
urlHistory.activeIndex > 0 ) {
settings.changeHash = false;
alreadyThere = true;
}
// Normally, we tack on a dialog hash key, but if this is the location of a stale dialog,
// we reuse the URL from the entry
url = ( active.url || "" );
// account for absolute urls instead of just relative urls use as hashes
if( !alreadyThere && url.indexOf("#") > -1 ) {
url += dialogHashKey;
} else {
url += "#" + dialogHashKey;
}
// tack on another dialogHashKey if this is the same as the initial hash
// this makes sure that a history entry is created for this dialog
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += dialogHashKey;
}
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text();
if ( !!newPageTitle && pageTitle === document.title ) {
pageTitle = newPageTitle;
}
if ( !toPage.jqmData( "title" ) ) {
toPage.jqmData( "title", pageTitle );
}
// Make sure we have a transition defined.
settings.transition = settings.transition ||
( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) ||
( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if ( !historyDir && alreadyThere ) {
urlHistory.getActive().pageUrl = pageUrl;
}
// Set the location hash.
if ( url && !settings.fromHashChange ) {
var params;
// rebuilding the hash here since we loose it earlier on
// TODO preserve the originally passed in path
if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) {
url = "#" + url;
}
// TODO the property names here are just silly
params = {
transition: settings.transition,
title: pageTitle,
pageUrl: pageUrl,
role: settings.role
};
if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) {
$.mobile.navigate( url, params, true);
} else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) {
$.mobile.navigate.history.add( url, params );
}
}
//set page title
document.title = pageTitle;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages( toPage, fromPage, settings.transition, settings.reverse )
.done(function( name, reverse, $to, $from, alreadyFocused ) {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if ( settings.duplicateCachedPage ) {
settings.duplicateCachedPage.remove();
}
// Send focus to the newly shown page. Moved from promise .done binding in transitionPages
// itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
// despite visibility: hidden addresses issue #2965
// https://github.com/jquery/jquery-mobile/issues/2965
if ( !alreadyFocused ) {
$.mobile.focusPage( toPage );
}
releasePageTransitionLock();
mpc.trigger( "pagechange", triggerData );
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink( ele )
{
while ( ele ) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl( ele )
{
// Find the closest page and extract out its url.
var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
base = documentBase.hrefNoHash;
if ( !url || !path.isPath( url ) ) {
url = base;
}
return path.makeUrlAbsolute( url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following deferred is resolved in the init file
$.mobile.navreadyDeferred = $.Deferred();
$.mobile._registerInternalEvents = function() {
var getAjaxFormData = function( $form, calculateOnly ) {
var url, ret = true, formData, vclickedName, method;
if ( !$.mobile.ajaxEnabled ||
// test that the form is, itself, ajax false
$form.is( ":jqmData(ajax='false')" ) ||
// test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$form.jqmHijackable().length ||
$form.attr( "target" ) ) {
return false;
}
url = $form.attr( "action" );
method = ( $form.attr( "method" ) || "get" ).toLowerCase();
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if ( !url ) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl( $form );
// NOTE: If the method is "get", we need to strip off the query string
// because it will get replaced with the new form data. See issue #5710.
if ( method === "get" ) {
url = path.parseUrl( url ).hrefNoSearch;
}
if ( url === documentBase.hrefNoHash ) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute( url, getClosestBaseUrl( $form ) );
if ( ( path.isExternal( url ) && !path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) {
return false;
}
if ( !calculateOnly ) {
formData = $form.serializeArray();
if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) {
vclickedName = $lastVClicked.attr( "name" );
if ( vclickedName ) {
// Make sure the last clicked element is included in the form
$.each( formData, function( key, value ) {
if ( value.name === vclickedName ) {
// Unset vclickedName - we've found it in the serialized data already
vclickedName = "";
return false;
}
});
if ( vclickedName ) {
formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } );
}
}
}
ret = {
url: url,
options: {
type: method,
data: $.param( formData ),
transition: $form.jqmData( "transition" ),
reverse: $form.jqmData( "direction" ) === "reverse",
reloadPage: true
}
};
}
return ret;
};
//bind to form submit events, handle with Ajax
$.mobile.document.delegate( "form", "submit", function( event ) {
var formData = getAjaxFormData( $( this ) );
if ( formData ) {
$.mobile.changePage( formData.url, formData.options );
event.preventDefault();
}
});
//add active state on vclick
$.mobile.document.bind( "vclick", function( event ) {
var $btn, btnEls, target = event.target, needClosest = false;
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create the which attr
if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
return;
}
// Record that this element was clicked, in case we need it for correct
// form submission during the "submit" handler above
$lastVClicked = $( target );
// Try to find a target element to which the active class will be applied
if ( $.data( target, "mobile-button" ) ) {
// If the form will not be submitted via AJAX, do not add active class
if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) {
return;
}
// We will apply the active state to this button widget - the parent
// of the input that was clicked will have the associated data
if ( target.parentNode ) {
target = target.parentNode;
}
} else {
target = findClosestLink( target );
if ( !( target && path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) {
return;
}
// TODO teach $.mobile.hijackable to operate on raw dom elements so the
// link wrapping can be avoided
if ( !$( target ).jqmHijackable().length ) {
return;
}
}
// Avoid calling .closest by using the data set during .buttonMarkup()
// List items have the button data in the parent of the element clicked
if ( !!~target.className.indexOf( "ui-link-inherit" ) ) {
if ( target.parentNode ) {
btnEls = $.data( target.parentNode, "buttonElements" );
}
// Otherwise, look for the data on the target itself
} else {
btnEls = $.data( target, "buttonElements" );
}
// If found, grab the button's outer element
if ( btnEls ) {
target = btnEls.outer;
} else {
needClosest = true;
}
$btn = $( target );
// If the outer element wasn't found by the our heuristics, use .closest()
if ( needClosest ) {
$btn = $btn.closest( ".ui-btn" );
}
if ( $btn.length > 0 && !$btn.hasClass( "ui-disabled" ) ) {
removeActiveLinkClass( true );
$activeClickedLink = $btn;
$activeClickedLink.addClass( $.mobile.activeBtnClass );
}
});
// click routing - direct to HTTP or Ajax, accordingly
$.mobile.document.bind( "click", function( event ) {
if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) {
return;
}
var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
// If there is no link associated with the click or its not a left
// click we want to ignore the click
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
return;
}
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function() {
window.setTimeout(function() { removeActiveLinkClass( true ); }, 200 );
};
//if there's a data-rel=back attr, go back in history
if ( $link.is( ":jqmData(rel='back')" ) ) {
$.mobile.back();
return false;
}
var baseUrl = getClosestBaseUrl( $link ),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
//if ajax is disabled, exit early
if ( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ) {
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if ( href.search( "#" ) !== -1 ) {
href = href.replace( /[^#]*#/, "" );
if ( !href ) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if ( path.isPath( href ) ) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute( href, baseUrl );
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest( documentUrl, href ) );
if ( isExternal ) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData( "transition" ),
reverse = $link.jqmData( "direction" ) === "reverse" ||
// deprecated - remove by 1.0
$link.jqmData( "back" ),
//this may need to be more specific as we use data-rel more
role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
$.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } );
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() {
var urls = [];
$( this ).find( "a:jqmData(prefetch)" ).each(function() {
var $link = $( this ),
url = $link.attr( "href" );
if ( url && $.inArray( url, urls ) === -1 ) {
urls.push( url );
$.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } );
}
});
});
$.mobile._handleHashChange = function( url, data ) {
//find first page via hash
var to = path.stripHash(url),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash, NOTE that the transition is derived from the previous
// history entry
changePageOptions = {
changeHash: false,
fromHashChange: true,
reverse: data.direction === "back"
};
$.extend( changePageOptions, data, {
transition: (urlHistory.getLast() || {}).transition || transition
});
// special case for dialogs
if ( urlHistory.activeIndex > 0 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if ( $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) ) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
if( data.direction === "back" ) {
$.mobile.back();
} else {
window.history.forward();
}
// prevent changePage call
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
to = data.pageUrl;
var active = $.mobile.urlHistory.getActive();
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend( changePageOptions, {
role: active.role,
transition: active.transition,
reverse: data.direction === "back"
});
}
}
//if to is defined, load it
if ( to ) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = !path.isPath( to ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
// If we're about to go to an initial URL that contains a reference to a non-existent
// internal page, go to the first page instead. We know that the initial hash refers to a
// non-existent page, because the initial hash did not end up in the initial urlHistory entry
if ( to === path.makeUrlAbsolute( '#' + urlHistory.initialDst, documentBase ) &&
urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace( dialogHashKey, "" ) ) {
to = $.mobile.firstPage;
}
$.mobile.changePage( to, changePageOptions );
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage( $.mobile.firstPage, changePageOptions );
}
};
// TODO roll the logic here into the handleHashChange method
$window.bind( "navigate", function( e, data ) {
var url;
if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) {
return;
}
url = $.event.special.navigate.originalEventName.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url;
if( !url ) {
url = $.mobile.path.parseLocation().hash;
}
if( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ){
url = location.href;
}
$.mobile._handleHashChange( url, data.state );
});
//set page min-heights to be device specific
$.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight );
$.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight );
};//navreadyDeferred done callback
$( function() { domreadyDeferred.resolve(); } );
$.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } );
})( jQuery );
/*
* fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flip = "fade";
})( jQuery, this );
/*
* fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flow = "fade";
})( jQuery, this );
/*
* fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.pop = "fade";
})( jQuery, this );
/*
* fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Use the simultaneous transitions handler for slide transitions
$.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slide = "fade";
})( jQuery, this );
/*
* fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slidedown = "fade";
})( jQuery, this );
/*
* fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slidefade = "fade";
})( jQuery, this );
/*
* fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slideup = "fade";
})( jQuery, this );
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.turn = "fade";
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
var page = $.mobile.closestPageData( $( e.target ) ), options;
if ( !page ) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
var $this = $( this ),
type = this.getAttribute( "type" ),
optType = options.degradeInputs[ type ] || "text";
if ( options.degradeInputs[ type ] ) {
var html = $( "<div>" ).html( $this.clone() ).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf( " type=" ) > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith( html.replace( findstr, repstr ) );
}
});
});
})( jQuery );
(function( $, window, undefined ) {
$.widget( "mobile.dialog", $.mobile.widget, {
options: {
closeBtn: "left",
closeBtnText: "Close",
overlayTheme: "a",
corners: true,
initSelector: ":jqmData(role='dialog')"
},
// Override the theme set by the page plugin on pageshow
_handlePageBeforeShow: function() {
this._isCloseable = true;
if ( this.options.overlayTheme ) {
this.element
.page( "removeContainerBackground" )
.page( "setContainerBackground", this.options.overlayTheme );
}
},
_handlePageBeforeHide: function() {
this._isCloseable = false;
},
_create: function() {
var self = this,
$el = this.element,
cornerClass = !!this.options.corners ? " ui-corner-all" : "",
dialogWrap = $( "<div/>", {
"role" : "dialog",
"class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass
});
$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
// Class the markup for dialog styling
// Set aria role
$el.wrapInner( dialogWrap );
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind( "vclick submit", function( event ) {
var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
active;
if ( $target.length && !$target.jqmData( "transition" ) ) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
.attr( "data-" + $.mobile.ns + "direction", "reverse" );
}
});
this._on( $el, {
pagebeforeshow: "_handlePageBeforeShow",
pagebeforehide: "_handlePageBeforeHide"
});
$.extend( this, {
_createComplete: false
});
this._setCloseBtn( this.options.closeBtn );
},
_setCloseBtn: function( value ) {
var self = this, btn, location;
if ( this._headerCloseButton ) {
this._headerCloseButton.remove();
this._headerCloseButton = null;
}
if ( value !== "none" ) {
// Sanitize value
location = ( value === "left" ? "left" : "right" );
btn = $( "<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" );
this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn );
if ( this._createComplete && $.fn.buttonMarkup ) {
btn.buttonMarkup();
}
this._createComplete = true;
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
//
// Use click rather than vclick in order to prevent the possibility of unintentionally
// reopening the dialog if the dialog opening item was directly under the close button.
btn.bind( "click", function() {
self.close();
});
this._headerCloseButton = btn;
}
},
_setOption: function( key, value ) {
if ( key === "closeBtn" ) {
this._setCloseBtn( value );
}
this._super( key, value );
},
// Close method goes back in history
close: function() {
var idx, dst, hist = $.mobile.navigate.history;
if ( this._isCloseable ) {
this._isCloseable = false;
// If the hash listening is enabled and there is at least one preceding history
// entry it's ok to go back. Initial pages with the dialog hash state are an example
// where the stack check is necessary
if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
$.mobile.back();
} else {
idx = Math.max( 0, hist.activeIndex - 1 );
dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
hist.previousIndex = hist.activeIndex;
hist.activeIndex = idx;
if ( !$.mobile.path.isPath( dst ) ) {
dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
}
$.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } );
}
}
}
});
//auto self-init widgets
$.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
$.mobile.dialog.prototype.enhance( this );
});
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
// NOTE bind used to force this binding to run before the buttonMarkup binding
// which expects .ui-footer top be applied in its gigantic selector
// TODO remove the buttonMarkup giant selector and move it to the various modules
// on which it depends
$.mobile.document.bind( "pagecreate", function( e ) {
var $page = $( e.target ),
o = $page.data( "mobile-page" ).options,
pageRole = $page.jqmData( "role" ),
pageTheme = o.theme;
$( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
.jqmEnhanceable()
.each(function() {
var $this = $( this ),
role = $this.jqmData( "role" ),
theme = $this.jqmData( "theme" ),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass( "ui-" + role );
//apply theming and markup modifications to page,header,content,footer
if ( role === "header" || role === "footer" ) {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass( "ui-bar-" + thisTheme )
// Add ARIA role
.attr( "role", role === "header" ? "banner" : "contentinfo" );
if ( role === "header") {
// Right,left buttons
$headeranchors = $this.children( "a, button" );
leftbtn = $headeranchors.hasClass( "ui-btn-left" );
rightbtn = $headeranchors.hasClass( "ui-btn-right" );
leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
}
// Auto-add back btn on pages beyond first view
if ( o.addBackBtn &&
role === "header" &&
$( ".ui-page" ).length > 1 &&
$page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
!leftbtn ) {
backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
// If theme is provided, override default inheritance
.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
.prependTo( $this );
}
// Page title
$this.children( "h1, h2, h3, h4, h5, h6" )
.addClass( "ui-title" )
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"role": "heading",
"aria-level": "1"
});
} else if ( role === "content" ) {
if ( contentTheme ) {
$this.addClass( "ui-body-" + ( contentTheme ) );
}
// Add ARIA role
$this.attr( "role", "main" );
}
});
});
})( jQuery );
(function( $, undefined ) {
// This function calls getAttribute, which should be safe for data-* attributes
var getAttrFixed = function( e, key ) {
var value = e.getAttribute( key );
return value === "true" ? true :
value === "false" ? false :
value === null ? undefined : value;
};
$.fn.buttonMarkup = function( options ) {
var $workingSet = this,
nsKey = "data-" + $.mobile.ns,
key;
// Enforce options to be of type string
options = ( options && ( $.type( options ) === "object" ) )? options : {};
for ( var i = 0; i < $workingSet.length; i++ ) {
var el = $workingSet.eq( i ),
e = el[ 0 ],
o = $.extend( {}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : getAttrFixed( e, nsKey + "icon" ),
iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed( e, nsKey + "iconpos" ),
theme: options.theme !== undefined ? options.theme : getAttrFixed( e, nsKey + "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
inline: options.inline !== undefined ? options.inline : getAttrFixed( e, nsKey + "inline" ),
shadow: options.shadow !== undefined ? options.shadow : getAttrFixed( e, nsKey + "shadow" ),
corners: options.corners !== undefined ? options.corners : getAttrFixed( e, nsKey + "corners" ),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed( e, nsKey + "iconshadow" ),
mini: options.mini !== undefined ? options.mini : getAttrFixed( e, nsKey + "mini" )
}, options ),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
hover = false,
state = "up",
// Button inner markup
buttonInner,
buttonText,
buttonIcon,
buttonElements;
for ( key in o ) {
if ( o[ key ] === undefined || o[ key ] === null ) {
el.removeAttr( nsKey + key );
} else {
e.setAttribute( nsKey + key, o[ key ] );
}
}
// Check if this element is already enhanced
buttonElements = $.data( ( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements" );
if ( buttonElements ) {
e = buttonElements.outer;
el = $( e );
buttonInner = buttonElements.inner;
buttonText = buttonElements.text;
// We will recreate this icon below
$( buttonElements.icon ).remove();
buttonElements.icon = null;
hover = buttonElements.hover;
state = buttonElements.state;
}
else {
buttonInner = document.createElement( o.wrapperEls );
buttonText = document.createElement( o.wrapperEls );
}
buttonIcon = o.icon ? document.createElement( "span" ) : null;
if ( attachEvents && !buttonElements ) {
attachEvents();
}
// if not, try to find closest theme container
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( el, "c" );
}
buttonClass = "ui-btn ";
buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" );
buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" );
buttonClass += o.shadow ? " ui-shadow" : "";
buttonClass += o.corners ? " ui-btn-corner-all" : "";
if ( o.mini !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize";
}
if ( o.inline !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `inline` style.
buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block";
}
if ( o.icon ) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if ( o.iconshadow ) {
iconClass += " ui-icon-shadow";
}
}
if ( o.iconpos ) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if ( o.iconpos === "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
}
if ( buttonElements ) {
el.removeClass( buttonElements.bcls || "" );
}
el.removeClass( "ui-link" ).addClass( buttonClass );
buttonInner.className = innerClass;
buttonText.className = textClass;
if ( !buttonElements ) {
buttonInner.appendChild( buttonText );
}
if ( buttonIcon ) {
buttonIcon.className = iconClass;
if ( !( buttonElements && buttonElements.icon ) ) {
buttonIcon.innerHTML = " ";
buttonInner.appendChild( buttonIcon );
}
}
while ( e.firstChild && !buttonElements ) {
buttonText.appendChild( e.firstChild );
}
if ( !buttonElements ) {
e.appendChild( buttonInner );
}
// Assign a structure containing the elements of this button to the elements of this button. This
// will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
buttonElements = {
hover : hover,
state : state,
bcls : buttonClass,
outer : e,
inner : buttonInner,
text : buttonText,
icon : buttonIcon
};
$.data( e, 'buttonElements', buttonElements );
$.data( buttonInner, 'buttonElements', buttonElements );
$.data( buttonText, 'buttonElements', buttonElements );
if ( buttonIcon ) {
$.data( buttonIcon, 'buttonElements', buttonElements );
}
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
wrapperEls: "span"
};
function closestEnabledButton( element ) {
var cname;
while ( element ) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && ( element.className + ' ' );
if ( cname && cname.indexOf( "ui-btn " ) > -1 && cname.indexOf( "ui-disabled " ) < 0 ) {
break;
}
element = element.parentNode;
}
return element;
}
function updateButtonClass( $btn, classToRemove, classToAdd, hover, state ) {
var buttonElements = $.data( $btn[ 0 ], "buttonElements" );
$btn.removeClass( classToRemove ).addClass( classToAdd );
if ( buttonElements ) {
buttonElements.bcls = $( document.createElement( "div" ) )
.addClass( buttonElements.bcls + " " + classToAdd )
.removeClass( classToRemove )
.attr( "class" );
if ( hover !== undefined ) {
buttonElements.hover = hover;
}
buttonElements.state = state;
}
}
var attachEvents = function() {
var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
$.mobile.document.bind( {
"vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
var theme,
$btn = $( closestEnabledButton( event.target ) ),
isTouchEvent = event.originalEvent && /^touch/.test( event.originalEvent.type ),
evt = event.type;
if ( $btn.length ) {
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
if ( evt === "vmousedown" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
hov = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}
} else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
updateButtonClass( $btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up" );
} else if ( evt === "vmouseover" || evt === "focus" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
foc = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}
} else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
updateButtonClass( $btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up" );
if ( hov ) {
clearTimeout( hov );
}
if ( foc ) {
clearTimeout( foc );
}
}
}
},
"focusin focus": function( event ) {
$( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
},
"focusout blur": function( event ) {
$( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
.jqmEnhanceable()
.not( "button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
.buttonMarkup();
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
collapsedIcon: "plus",
expandedIcon: "minus",
iconpos: "left",
theme: null,
contentTheme: null,
inset: true,
corners: true,
mini: false,
initSelector: ":jqmData(role='collapsible')"
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ),
collapsibleClasses = "";
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon;
// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon;
// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos;
// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
if ( collapsibleSet.jqmData( "inset" ) !== undefined ) {
o.inset = collapsibleSet.jqmData( "inset" );
} else {
o.inset = true;
}
// Set corners for individual collapsibles to false when in a collapsible-set
o.corners = false;
// Gets the preference for mini in the set
if ( !o.mini ) {
o.mini = collapsibleSet.jqmData( "mini" );
}
} else {
// get inherited theme if not a set and no theme has been set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
}
if ( !!o.inset ) {
collapsibleClasses += " ui-collapsible-inset";
if ( !!o.corners ) {
collapsibleClasses += " ui-corner-all" ;
}
}
if ( o.contentTheme ) {
collapsibleClasses += " ui-collapsible-themed-content";
collapsibleContent.addClass( "ui-body-" + o.contentTheme );
}
if ( collapsibleClasses !== "" ) {
collapsible.addClass( collapsibleClasses );
}
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconpos: o.iconpos,
icon: o.collapsedIcon,
mini: o.mini,
theme: o.theme
});
//events
collapsible
.bind( "expand collapse", function( event ) {
if ( !event.isDefaultPrevented() ) {
var $this = $( this ),
isCollapse = ( event.type === "collapse" );
event.preventDefault();
collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
.end()
.find( "a" ).first().removeClass( $.mobile.activeBtnClass );
$this.toggleClass( "ui-collapsible-collapsed", isCollapse );
collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
collapsibleContent.trigger( "updatelayout" );
}
})
.trigger( o.collapsed ? "collapse" : "expand" );
collapsibleHeading
.bind( "tap", function( event ) {
collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
})
.bind( "click", function( event ) {
var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
event.stopPropagation();
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsible.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.addFirstLastClasses = {
_getVisibles: function( $els, create ) {
var visibles;
if ( create ) {
visibles = $els.not( ".ui-screen-hidden" );
} else {
visibles = $els.filter( ":visible" );
if ( visibles.length === 0 ) {
visibles = $els.not( ".ui-screen-hidden" );
}
}
return visibles;
},
_addFirstLastClasses: function( $els, $visibles, create ) {
$els.removeClass( "ui-first-child ui-last-child" );
$visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" );
if ( !create ) {
this.element.trigger( "updatelayout" );
}
}
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
options: {
initSelector: ":jqmData(role='collapsible-set')"
},
_create: function() {
var $el = this.element.addClass( "ui-collapsible-set" ),
o = this.options;
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = $el.jqmData( "content-theme" );
}
// Inherit the corner styling from collapsible-set
if ( !o.corners ) {
o.corners = $el.jqmData( "corners" );
}
if ( $el.jqmData( "inset" ) !== undefined ) {
o.inset = $el.jqmData( "inset" );
}
o.inset = o.inset !== undefined ? o.inset : true;
o.corners = o.corners !== undefined ? o.corners : true;
if ( !!o.corners && !!o.inset ) {
$el.addClass( "ui-corner-all" );
}
// Initialize the collapsible set if it's not already initialized
if ( !$el.jqmData( "collapsiblebound" ) ) {
$el
.jqmData( "collapsiblebound", true )
.bind( "expand", function( event ) {
var closestCollapsible = $( event.target )
.closest( ".ui-collapsible" );
if ( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
closestCollapsible
.siblings( ".ui-collapsible" )
.trigger( "collapse" );
}
});
}
},
_init: function() {
var $el = this.element,
collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
this._refresh( "true" );
// Because the corners are handled by the collapsible itself and the default state is collapsed
// That was causing https://github.com/jquery/jquery-mobile/issues/4116
expanded.trigger( "expand" );
},
_refresh: function( create ) {
var collapsiblesInSet = this.element.children( ":jqmData(role='collapsible')" );
$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
},
refresh: function() {
this._refresh( false );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
// filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
$.fn.fieldcontain = function( options ) {
return this
.addClass( "ui-field-contain ui-body ui-br" )
.contents().filter( function() {
return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
}).remove();
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
});
})( jQuery );
(function( $, undefined ) {
$.fn.grid = function( options ) {
return this.each(function() {
var $this = $( this ),
o = $.extend({
grid: null
}, options ),
$kids = $this.children(),
gridCols = { solo:1, a:2, b:3, c:4, d:5 },
grid = o.grid,
iterator;
if ( !grid ) {
if ( $kids.length <= 5 ) {
for ( var letter in gridCols ) {
if ( gridCols[ letter ] === $kids.length ) {
grid = letter;
}
}
} else {
grid = "a";
$this.addClass( "ui-grid-duo" );
}
}
iterator = gridCols[grid];
$this.addClass( "ui-grid-" + grid );
$kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
if ( iterator > 1 ) {
$kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
}
if ( iterator > 2 ) {
$kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" );
}
if ( iterator > 3 ) {
$kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" );
}
if ( iterator > 4 ) {
$kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" );
}
});
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function() {
var $navbar = this.element,
$navbtns = $navbar.find( "a" ),
iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
this.options.iconpos : undefined;
$navbar.addClass( "ui-navbar ui-mini" )
.attr( "role", "navigation" )
.find( "ul" )
.jqmEnhanceable()
.grid({ grid: this.options.grid });
$navbtns.buttonMarkup({
corners: false,
shadow: false,
inline: true,
iconpos: iconpos
});
$navbar.delegate( "a", "vclick", function( event ) {
// ui-btn-inner is returned as target
var target = $( event.target ).is( "a" ) ? $( this ) : $( this ).parent( "a" );
if ( !target.is( ".ui-disabled, .ui-btn-active" ) ) {
$navbtns.removeClass( $.mobile.activeBtnClass );
$( this ).addClass( $.mobile.activeBtnClass );
// The code below is a workaround to fix #1181
var activeBtn = $( this );
$( document ).one( "pagehide", function() {
activeBtn.removeClass( $.mobile.activeBtnClass );
});
}
});
// Buttons in the navbar with ui-state-persist class should regain their active state before page show
$navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
$navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.navbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget( "mobile.listview", $.mobile.widget, $.extend( {
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
icon: "arrow-r",
splitIcon: "arrow-r",
splitTheme: "b",
corners: true,
shadow: true,
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this,
listviewClasses = "";
listviewClasses += t.options.inset ? " ui-listview-inset" : "";
if ( !!t.options.inset ) {
listviewClasses += t.options.corners ? " ui-corner-all" : "";
listviewClasses += t.options.shadow ? " ui-shadow" : "";
}
// create listview markup
t.element.addClass(function( i, orig ) {
return orig + " ui-listview" + listviewClasses;
});
t.refresh( true );
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function( ele, lcName, ucName ) {
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
results.push( ele );
}
ele = ele.nextSibling;
}
return $( results );
},
_addThumbClasses: function( containers ) {
var i, img, len = containers.length;
for ( i = 0; i < len; i++ ) {
img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
if ( img.length ) {
img.addClass( "ui-li-thumb" );
$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
}
}
},
refresh: function( create ) {
this.parentPage = this.element.closest( ".ui-page" );
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
listsplittheme = $list.jqmData( "splittheme" ),
listspliticon = $list.jqmData( "spliticon" ),
listicon = $list.jqmData( "icon" ),
li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
ol = !!$.nodeName( $list[ 0 ], "ol" ),
jsCount = !$.support.cssPseudoElement,
start = $list.attr( "start" ),
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon;
if ( ol && jsCount ) {
$list.find( ".ui-li-dec" ).remove();
}
if ( ol ) {
// Check if a start attribute has been set while taking a value of 0 into account
if ( start || start === 0 ) {
if ( !jsCount ) {
startCount = parseInt( start , 10 ) - 1;
$list.css( "counter-reset", "listnumbering " + startCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
item = li.eq( pos );
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if ( create || !item.hasClass( "ui-li" ) ) {
itemTheme = item.jqmData( "theme" ) || o.theme;
a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
var isDivider = ( item.jqmData( "role" ) === "list-divider" );
if ( a.length && !isDivider ) {
icon = item.jqmData( "icon" );
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
theme: itemTheme
});
if ( ( icon !== false ) && ( a.length === 1 ) ) {
item.addClass( "ui-li-has-arrow" );
}
a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
if ( a.length > 1 ) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
linkIcon = last.jqmData( "icon" );
last.appendTo( item )
.attr( "title", $.trim(last.getEncodedText()) )
.addClass( "ui-li-link-alt" )
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: "notext"
})
.find( ".ui-btn-inner" )
.append(
$( document.createElement( "span" ) ).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
// link icon overrides list item icon overrides ul element overrides options
icon: linkIcon || icon || listspliticon || o.splitIcon
})
);
}
} else if ( isDivider ) {
itemClass += " ui-li-divider ui-bar-" + ( item.jqmData( "theme" ) || dividertheme );
item.attr( "role", "heading" );
if ( ol ) {
//reset counter when a divider heading is encountered
if ( start || start === 0 ) {
if ( !jsCount ) {
newStartCount = parseInt( start , 10 ) - 1;
item.css( "counter-reset", "listnumbering " + newStartCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
} else {
itemClass += " ui-li-static ui-btn-up-" + itemTheme;
}
}
if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );
countParent.addClass( "ui-li-jsnumbering" )
.prepend( "<span class='ui-li-dec'>" + ( counter++ ) + ". </span>" );
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if ( !itemClassDict[ itemClass ] ) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push( item[ 0 ] );
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for ( itemClass in itemClassDict ) {
$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
}
$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
.end()
.find( "p, dl" ).addClass( "ui-li-desc" )
.end()
.find( ".ui-li-aside" ).each(function() {
var $this = $( this );
$this.prependTo( $this.parent() ); //shift aside to front for css float
})
.end()
.find( ".ui-li-count" ).each(function() {
$( this ).closest( "li" ).addClass( "ui-li-has-count" );
}).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses( li );
this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
// autodividers binds to this to redraw dividers after the listview refresh
this._trigger( "afterrefresh" );
},
//create a string for ID/subpage url creation
_idStringEscape: function( str ) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest( ".ui-page" ),
parentUrl = parentPage.jqmData( "url" ),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr( "id" ),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
hasSubPages;
if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
var self = this,
list = $( this ),
listId = list.attr( "id" ) || parentListId + "-" + i,
parent = list.parent(),
nodeElsFull = $( list.prevAll().toArray().reverse() ),
nodeEls = nodeElsFull.length ? nodeElsFull : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData( "theme" ) || o.theme,
countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
.parent()
.before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
.after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>" ) : "" )
.parent()
.appendTo( $.mobile.pageContainer );
newPage.page();
anchor = parent.find( 'a:first' );
if ( !anchor.length ) {
anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
}
anchor.attr( "href", "#" + id );
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if ( hasSubPages &&
parentPage.is( ":jqmData(external-page='true')" ) &&
parentPage.data( "mobile-page" ).options.domCache === false ) {
var newRemove = function( e, ui ) {
var nextPage = ui.nextPage, npURL,
prEvent = new $.Event( "pageremove" );
if ( ui.nextPage ) {
npURL = nextPage.jqmData( "url" );
if ( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ) {
self.childPages().remove();
parentPage.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
parentPage.removeWithDependents();
}
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind( "pagehide.remove" )
.bind( "pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function() {
var parentUrl = this.parentPage.jqmData( "url" );
return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey + "')" );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.listview.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $ ) {
var meta = $( "meta[name=viewport]" ),
initialContent = meta.attr( "content" ),
disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
$.mobile.zoom = $.extend( {}, {
enabled: !disabledInitially,
locked: false,
disable: function( lock ) {
if ( !disabledInitially && !$.mobile.zoom.locked ) {
meta.attr( "content", disabledZoom );
$.mobile.zoom.enabled = false;
$.mobile.zoom.locked = lock || false;
}
},
enable: function( unlock ) {
if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) {
meta.attr( "content", enabledZoom );
$.mobile.zoom.enabled = true;
$.mobile.zoom.locked = false;
}
},
restore: function() {
if ( !disabledInitially ) {
meta.attr( "content", initialContent );
$.mobile.zoom.enabled = true;
}
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "mobile.textinput", $.mobile.widget, {
options: {
theme: null,
mini: false,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",
clearBtn: false,
clearSearchButtonText: null, //deprecating for 1.3...
clearBtnText: "clear text",
disabled: false
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
themeclass = " ui-body-" + theme,
miniclass = o.mini ? " ui-mini" : "",
isSearch = input.is( "[type='search'], :jqmData(type='search')" ),
focusedEl,
clearbtn,
clearBtnText = o.clearSearchButtonText || o.clearBtnText,
clearBtnBlacklist = input.is( "textarea, :jqmData(type='range')" ),
inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist,
inputNeedsWrap = input.is( "input" ) && !input.is( ":jqmData(type='range')" );
function toggleClear() {
setTimeout( function() {
clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
}, 0 );
}
$( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
focusedEl = input.addClass( "ui-input-text ui-body-"+ theme );
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute( "autocorrect", "off" );
input[0].setAttribute( "autocomplete", "off" );
}
//"search" and "text" input widgets
if ( isSearch ) {
focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
} else if ( inputNeedsWrap ) {
focusedEl = input.wrap( "<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>" ).parent();
}
if( inputNeedsClearBtn || isSearch ) {
clearbtn = $( "<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>" )
.bind( "click", function( event ) {
input
.val( "" )
.focus()
.trigger( "change" );
clearbtn.addClass( "ui-input-clear-hidden" );
event.preventDefault();
})
.appendTo( focusedEl )
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true,
mini: o.mini
});
if ( !isSearch ) {
focusedEl.addClass( "ui-input-has-clear" );
}
toggleClear();
input.bind( "paste cut keyup input focus change blur", toggleClear );
}
else if ( !inputNeedsWrap && !isSearch ) {
input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
}
input.focus(function() {
// In many situations, iOS will zoom into the input upon tap, this prevents that from happening
if ( o.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
focusedEl.addClass( $.mobile.focusClass );
})
.blur(function() {
focusedEl.removeClass( $.mobile.focusClass );
if ( o.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
// Autogrow
if ( input.is( "textarea" ) ) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyupTimeout;
this._keyup = function() {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if ( clientHeight < scrollHeight ) {
var paddingTop = parseFloat( input.css( "padding-top" ) ),
paddingBottom = parseFloat( input.css( "padding-bottom" ) ),
paddingHeight = paddingTop + paddingBottom;
input.height( scrollHeight - paddingHeight + extraLineHeight );
}
};
input.on( "keyup change input paste", function() {
clearTimeout( keyupTimeout );
keyupTimeout = setTimeout( self._keyup, keyupTimeoutBuffer );
});
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
this._on( true, $.mobile.document, { "pagechange": "_keyup" });
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ( $.trim( input.val() ) ) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
this._on( true, $.mobile.window, {"load": "_keyup"});
}
}
if ( input.attr( "disabled" ) ) {
this.disable();
}
},
disable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsDisabled = this.element.attr( "disabled", true ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsDisabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.addClass( "ui-disabled" );
return this._setOption( "disabled", true );
},
enable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsEnabled = this.element.attr( "disabled", false ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsEnabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.removeClass( "ui-disabled" );
return this._setOption( "disabled", false );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.textinput.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterReveal = false;
// TODO rename callback/deprecate and default to the item itself as the first argument
var defaultFilterCallback = function( text, searchValue, item ) {
return text.toString().toLowerCase().indexOf( searchValue ) === -1;
};
$.mobile.listview.prototype.options.filterCallback = defaultFilterCallback;
$.mobile.document.delegate( "ul, ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.filter ) {
return;
}
if ( listview.options.filterReveal ) {
list.children().addClass( "ui-screen-hidden" );
}
var wrapper = $( "<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}).submit( function( e ) {
e.preventDefault();
search.blur();
}),
onKeyUp = function( e ) {
var $this = $( this ),
val = this.value.toLowerCase(),
listItems = null,
li = list.children(),
lastval = $this.jqmData( "lastval" ) + "",
childItems = false,
itemtext = "",
item,
// Check if a custom filter callback applies
isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback;
if ( lastval && lastval === val ) {
// Execute the handler only once per value change
return;
}
listview._trigger( "beforefilter", "beforefilter", { input: this } );
// Change val as lastval for next execution
$this.jqmData( "lastval" , val );
if ( isCustomFilterCallback || val.length < lastval.length || val.indexOf( lastval ) !== 0 ) {
// Custom filter callback applies or removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children( ":not(.ui-screen-hidden)" );
if ( !listItems.length && listview.options.filterReveal ) {
listItems = list.children( ".ui-screen-hidden" );
}
}
if ( val ) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for ( var i = listItems.length - 1; i >= 0; i-- ) {
item = $( listItems[ i ] );
itemtext = item.jqmData( "filtertext" ) || item.text();
if ( item.is( "li:jqmData(role=list-divider)" ) ) {
item.toggleClass( "ui-filter-hidequeue" , !childItems );
// New bucket!
childItems = false;
} else if ( listview.options.filterCallback( itemtext, val, item ) ) {
//mark to be hidden
item.toggleClass( "ui-filter-hidequeue" , true );
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter( ":not(.ui-filter-hidequeue)" )
.toggleClass( "ui-screen-hidden", false );
// Hide items, marked to be hidden
listItems
.filter( ".ui-filter-hidequeue" )
.toggleClass( "ui-screen-hidden", true )
.toggleClass( "ui-filter-hidequeue", false );
} else {
//filtervalue is empty => show all
listItems.toggleClass( "ui-screen-hidden", !!listview.options.filterReveal );
}
listview._addFirstLastClasses( li, listview._getVisibles( li, false ), false );
},
search = $( "<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr( "data-" + $.mobile.ns + "type", "search" )
.jqmData( "lastval", "" )
.bind( "keyup change input", onKeyUp )
.appendTo( wrapper )
.textinput();
if ( listview.options.inset ) {
wrapper.addClass( "ui-listview-filter-inset" );
}
wrapper.bind( "submit", function() {
return false;
})
.insertBefore( list );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.autodividers = false;
$.mobile.listview.prototype.options.autodividersSelector = function( elt ) {
// look for the text in the given element
var text = $.trim( elt.text() ) || null;
if ( !text ) {
return null;
}
// create the text for the divider (first uppercased letter)
text = text.slice( 0, 1 ).toUpperCase();
return text;
};
$.mobile.document.delegate( "ul,ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.autodividers ) {
return;
}
var replaceDividers = function () {
list.find( "li:jqmData(role='list-divider')" ).remove();
var lis = list.find( 'li' ),
lastDividerText = null, li, dividerText;
for ( var i = 0; i < lis.length ; i++ ) {
li = lis[i];
dividerText = listview.options.autodividersSelector( $( li ) );
if ( dividerText && lastDividerText !== dividerText ) {
var divider = document.createElement( 'li' );
divider.appendChild( document.createTextNode( dividerText ) );
divider.setAttribute( 'data-' + $.mobile.ns + 'role', 'list-divider' );
li.parentNode.insertBefore( divider, li );
}
lastDividerText = dividerText;
}
};
var afterListviewRefresh = function () {
list.unbind( 'listviewafterrefresh', afterListviewRefresh );
replaceDividers();
listview.refresh();
list.bind( 'listviewafterrefresh', afterListviewRefresh );
};
afterListviewRefresh();
});
})( jQuery );
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.formReset = {
_handleFormReset: function() {
this._on( this.element.closest( "form" ), {
reset: function() {
this._delay( "_reset" );
}
});
}
};
})( jQuery );
/*
* "checkboxradio" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.checkboxradio", $.mobile.widget, $.extend( {
options: {
theme: null,
mini: false,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
inheritAttr = function( input, dataAttr ) {
return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr );
},
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
parentLabel = $( input ).closest( "label" ),
label = parentLabel.length ? parentLabel : $( input ).closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ).first(),
inputtype = input[0].type,
mini = inheritAttr( input, "mini" ) || o.mini,
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
iconpos = inheritAttr( input, "iconpos" ),
checkedClass = "ui-" + checkedState,
uncheckedClass = "ui-" + uncheckedState;
if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
return;
}
// Expose for other methods
$.extend( this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedState,
uncheckedicon: uncheckedState
});
// If there's no selected theme check the data attr
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
label.buttonMarkup({
theme: o.theme,
icon: uncheckedState,
shadow: false,
mini: mini,
iconpos: iconpos
});
// Wrap the input + label in a div
var wrapper = document.createElement('div');
wrapper.className = 'ui-' + inputtype;
input.add( label ).wrapAll( wrapper );
label.bind({
vmouseover: function( event ) {
if ( $( this ).parent().is( ".ui-disabled" ) ) {
event.stopPropagation();
}
},
vclick: function( event ) {
if ( input.is( ":disabled" ) ) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler( 'click' );
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not( input ).prop( "checked", false );
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function() {
self._cacheVals();
},
vclick: function() {
var $this = $( this );
// Adds checked attribute to checked input when keyboard is used
if ( $this.is( ":checked" ) ) {
$this.prop( "checked", true);
self._getInputSet().not( $this ).prop( "checked", false );
} else {
$this.prop( "checked", false );
}
self._updateAll();
},
focus: function() {
label.addClass( $.mobile.focusClass );
},
blur: function() {
label.removeClass( $.mobile.focusClass );
}
});
this._handleFormReset();
this.refresh();
},
_cacheVals: function() {
this._getInputSet().each(function() {
$( this ).jqmData( "cacheVal", this.checked );
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function() {
if ( this.inputtype === "checkbox" ) {
return this.element;
}
return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" )
.find( "input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']" );
},
_updateAll: function() {
var self = this;
this._getInputSet().each(function() {
var $this = $( this );
if ( this.checked || self.inputtype === "checkbox" ) {
$this.trigger( "change" );
}
})
.checkboxradio( "refresh" );
},
_reset: function() {
this.refresh();
},
refresh: function() {
var input = this.element[ 0 ],
active = " " + $.mobile.activeBtnClass,
checkedClass = this.checkedClass + ( this.element.parents( ".ui-controlgroup-horizontal" ).length ? active : "" ),
label = this.label;
if ( input.checked ) {
label.removeClass( this.uncheckedClass + active ).addClass( checkedClass ).buttonMarkup( { icon: this.checkedicon } );
} else {
label.removeClass( checkedClass ).addClass( this.uncheckedClass ).buttonMarkup( { icon: this.uncheckedicon } );
}
if ( input.disabled ) {
this.disable();
} else {
this.enable();
}
},
disable: function() {
this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
},
enable: function() {
this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
corners: true,
shadow: true,
iconshadow: true,
inline: null,
mini: null,
initSelector: "button, [type='button'], [type='submit'], [type='reset']"
},
_create: function() {
var $el = this.element,
$button,
// create a copy of this.options we can pass to buttonMarkup
o = ( function( tdo ) {
var key, ret = {};
for ( key in tdo ) {
if ( tdo[ key ] !== null && key !== "initSelector" ) {
ret[ key ] = tdo[ key ];
}
}
return ret;
} )( this.options ),
classes = "",
$buttonPlaceholder;
// if this is a link, check if it's been enhanced and, if not, use the right function
if ( $el[ 0 ].tagName === "A" ) {
if ( !$el.hasClass( "ui-btn" ) ) {
$el.buttonMarkup();
}
return;
}
// get the inherited theme
// TODO centralize for all widgets
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
classes = "ui-btn-left";
}
if ( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
classes = "ui-btn-right";
}
if ( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
if ( classes ) {
classes += " ui-submit";
} else {
classes = "ui-submit";
}
}
$( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
// Add ARIA role
this.button = $( "<div></div>" )
[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
.insertBefore( $el )
.buttonMarkup( o )
.addClass( classes )
.append( $el.addClass( "ui-btn-hidden" ) );
$button = this.button;
$el.bind({
focus: function() {
$button.addClass( $.mobile.focusClass );
},
blur: function() {
$button.removeClass( $.mobile.focusClass );
}
});
this.refresh();
},
_setOption: function( key, value ) {
var op = {};
op[ key ] = value;
if ( key !== "initSelector" ) {
this.button.buttonMarkup( op );
// Record the option change in the options and in the DOM data-* attributes
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
}
this._super( "_setOption", key, value );
},
enable: function() {
this.element.attr( "disabled", false );
this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
},
refresh: function() {
var $el = this.element;
if ( $el.prop("disabled") ) {
this.disable();
} else {
this.enable();
}
// Grab the button's text element from its implementation-independent data item
$( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.button.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.slider", $.mobile.widget, $.extend( {
widgetEventPrefix: "slide",
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
mini: false,
highlight: false
},
_create: function() {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme( control, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
isSelect = this.isToggleSwitch = cType === "select",
isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ),
selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "",
controlID = control.attr( "id" ),
$label = $( "[for='" + controlID + "']" ),
labelID = $label.attr( "id" ) || controlID + "-label",
label = $label.attr( "id", labelID ),
min = !this.isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0,
max = !this.isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
step = window.parseFloat( control.attr( "step" ) || 1 ),
miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "",
domHandle = document.createElement( "a" ),
handle = $( domHandle ),
domSlider = document.createElement( "div" ),
slider = $( domSlider ),
valuebg = this.options.highlight && !this.isToggleSwitch ? (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( slider );
})() : false,
options,
wrapper;
domHandle.setAttribute( "href", "#" );
domSlider.setAttribute( "role", "application" );
domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ",selectClass," ui-btn-down-",trackTheme," ui-btn-corner-all", miniClass].join( "" );
domHandle.className = "ui-slider-handle";
domSlider.appendChild( domHandle );
handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": this._value(),
"aria-valuetext": this._value(),
"title": this._value(),
"aria-labelledby": labelID
});
$.extend( this, {
slider: slider,
handle: handle,
type: cType,
step: step,
max: max,
min: min,
valuebg: valuebg,
isRangeslider: isRangeslider,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if ( this.isToggleSwitch ) {
wrapper = document.createElement( "div" );
wrapper.className = "ui-slider-inneroffset";
for ( var j = 0, length = domSlider.childNodes.length; j < length; j++ ) {
wrapper.appendChild( domSlider.childNodes[j] );
}
domSlider.appendChild( wrapper );
// slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
options = control.find( "option" );
for ( var i = 0, optionsCount = options.length; i < optionsCount; i++ ) {
var side = !i ? "b" : "a",
sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ),
sliderLabel = document.createElement( "div" ),
sliderImg = document.createElement( "span" );
sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join( "" );
sliderImg.setAttribute( "role", "img" );
sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) );
$( sliderImg ).prependTo( slider );
}
self._labels = $( ".ui-slider-label", slider );
}
label.addClass( "ui-slider" );
// monitor the input for updated values
control.addClass( this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" );
this._on( control, {
"change": "_controlChange",
"keyup": "_controlKeyup",
"blur": "_controlBlur",
"vmouseup": "_controlVMouseUp"
});
slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) )
.bind( "vclick", false );
// We have to instantiate a new function object for the unbind to work properly
// since the method itself is defined in the prototype (causing it to unbind everything)
this._on( document, { "vmousemove": "_preventDocumentDrag" });
this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" });
slider.insertAfter( control );
// wrap in a div for styling purposes
if ( !this.isToggleSwitch && !isRangeslider ) {
wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>";
control.add( slider ).wrapAll( wrapper );
}
// Only add focus class to toggle switch, sliders get it automatically from ui-btn
if ( this.isToggleSwitch ) {
this.handle.bind({
focus: function() {
slider.addClass( $.mobile.focusClass );
},
blur: function() {
slider.removeClass( $.mobile.focusClass );
}
});
}
// bind the handle event callbacks and set the context to the widget instance
this._on( this.handle, {
"vmousedown": "_handleVMouseDown",
"keydown": "_handleKeydown",
"keyup": "_handleKeyup"
});
this.handle.bind( "vclick", false );
this._handleFormReset();
this.refresh( undefined, undefined, true );
},
_controlChange: function( event ) {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if ( this._trigger( "controlchange", event ) === false ) {
return false;
}
if ( !this.mouseMoved ) {
this.refresh( this._value(), true );
}
},
_controlKeyup: function( event ) { // necessary?
this.refresh( this._value(), true, true );
},
_controlBlur: function( event ) {
this.refresh( this._value(), true );
},
// it appears the clicking the up and down buttons in chrome on
// range/number inputs doesn't trigger a change until the field is
// blurred. Here we check thif the value has changed and refresh
_controlVMouseUp: function( event ) {
this._checkedRefresh();
},
// NOTE force focus on handle
_handleVMouseDown: function( event ) {
this.handle.focus();
},
_handleKeydown: function( event ) {
var index = this._value();
if ( this.options.disabled ) {
return;
}
// In all cases prevent the default and mark the handle as active
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
this.handle.addClass( "ui-state-active" );
}
break;
}
// move the slider according to the keypress
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
this.refresh( this.min );
break;
case $.mobile.keyCode.END:
this.refresh( this.max );
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
this.refresh( index + this.step );
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
this.refresh( index - this.step );
break;
}
}, // remove active mark
_handleKeyup: function( event ) {
if ( this._keySliding ) {
this._keySliding = false;
this.handle.removeClass( "ui-state-active" );
}
},
_sliderVMouseDown: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) {
return false;
}
if ( this._trigger( "beforestart", event ) === false ) {
return false;
}
this.dragging = true;
this.userModified = false;
this.mouseMoved = false;
if ( this.isToggleSwitch ) {
this.beforeStart = this.element[0].selectedIndex;
}
this.refresh( event );
this._trigger( "start" );
return false;
},
_sliderVMouseUp: function() {
if ( this.dragging ) {
this.dragging = false;
if ( this.isToggleSwitch ) {
// make the handle move with a smooth transition
this.handle.addClass( "ui-slider-handle-snapping" );
if ( this.mouseMoved ) {
// this is a drag, change the value only if user dragged enough
if ( this.userModified ) {
this.refresh( this.beforeStart === 0 ? 1 : 0 );
} else {
this.refresh( this.beforeStart );
}
} else {
// this is just a click, change the value
this.refresh( this.beforeStart === 0 ? 1 : 0 );
}
}
this.mouseMoved = false;
this._trigger( "stop" );
return false;
}
},
_preventDocumentDrag: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this._trigger( "drag", event ) === false) {
return false;
}
if ( this.dragging && !this.options.disabled ) {
// this.mouseMoved must be updated before refresh() because it will be used in the control "change" event
this.mouseMoved = true;
if ( this.isToggleSwitch ) {
// make the handle move in sync with the mouse
this.handle.removeClass( "ui-slider-handle-snapping" );
}
this.refresh( event );
// only after refresh() you can calculate this.userModified
this.userModified = this.beforeStart !== this.element[0].selectedIndex;
return false;
}
},
_checkedRefresh: function() {
if ( this.value !== this._value() ) {
this.refresh( this._value() );
}
},
_value: function() {
return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ;
},
_reset: function() {
this.refresh( undefined, false, true );
},
refresh: function( val, isfromControl, preventInputUpdate ) {
// NOTE: we don't return here because we want to support programmatic
// alteration of the input value, which should still update the slider
var self = this,
parentTheme = $.mobile.getInheritedTheme( this.element, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
left, width, data, tol;
self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track"," ui-btn-down-" + trackTheme,' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini":""].join( "" );
if ( this.options.disabled || this.element.attr( "disabled" ) ) {
this.disable();
}
// set the stored value for comparison later
this.value = this._value();
if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) {
this.valuebg = (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( self.slider );
})();
}
this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true });
var pxStep, percent,
control = this.element,
isInput = !this.isToggleSwitch,
optionElements = isInput ? [] : control.find( "option" ),
min = isInput ? parseFloat( control.attr( "min" ) ) : 0,
max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1,
step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1;
if ( typeof val === "object" ) {
data = val;
// a slight tolerance helped get to the ends of the slider
tol = 8;
left = this.slider.offset().left;
width = this.slider.width();
pxStep = width/((max-min)/step);
if ( !this.dragging ||
data.pageX < left - tol ||
data.pageX > left + width + tol ) {
return;
}
if ( pxStep > 1 ) {
percent = ( ( data.pageX - left ) / width ) * 100;
} else {
percent = Math.round( ( ( data.pageX - left ) / width ) * 100 );
}
} else {
if ( val == null ) {
val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
}
percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
}
if ( isNaN( percent ) ) {
return;
}
var newval = ( percent / 100 ) * ( max - min ) + min;
//from jQuery UI slider, the following source will round to the nearest step
var valModStep = ( newval - min ) % step;
var alignValue = newval - valModStep;
if ( Math.abs( valModStep ) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
var percentPerStep = 100/((max-min)/step);
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see jQueryUI: #4124)
newval = parseFloat( alignValue.toFixed(5) );
if ( typeof pxStep === "undefined" ) {
pxStep = width / ( (max-min) / step );
}
if ( pxStep > 1 && isInput ) {
percent = ( newval - min ) * percentPerStep * ( 1 / step );
}
if ( percent < 0 ) {
percent = 0;
}
if ( percent > 100 ) {
percent = 100;
}
if ( newval < min ) {
newval = min;
}
if ( newval > max ) {
newval = max;
}
this.handle.css( "left", percent + "%" );
this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) );
this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
if ( this.valuebg ) {
this.valuebg.css( "width", percent + "%" );
}
// drag the label widths
if ( this._labels ) {
var handlePercent = this.handle.width() / this.slider.width() * 100,
aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
this._labels.each(function() {
var ab = $( this ).is( ".ui-slider-label-a" );
$( this ).width( ( ab ? aPercent : bPercent ) + "%" );
});
}
if ( !preventInputUpdate ) {
var valueChanged = false;
// update control"s value
if ( isInput ) {
valueChanged = control.val() !== newval;
control.val( newval );
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if ( this._trigger( "beforechange", val ) === false) {
return false;
}
if ( !isfromControl && valueChanged ) {
control.trigger( "change" );
}
}
},
enable: function() {
this.element.attr( "disabled", false );
this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.slider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.rangeslider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: ":jqmData(role='rangeslider')",
mini: false,
highlight: true
},
_create: function() {
var secondLabel,
$el = this.element,
elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider",
_inputFirst = $el.find( "input" ).first(),
_inputLast = $el.find( "input" ).last(),
label = $el.find( "label" ).first(),
_sliderFirst = $.data( _inputFirst.get(0), "mobileSlider" ).slider,
_sliderLast = $.data( _inputLast.get(0), "mobileSlider" ).slider,
firstHandle = $.data( _inputFirst.get(0), "mobileSlider" ).handle,
_sliders = $( "<div class=\"ui-rangeslider-sliders\" />" ).appendTo( $el );
if ( $el.find( "label" ).length > 1 ) {
secondLabel = $el.find( "label" ).last().hide();
}
_inputFirst.addClass( "ui-rangeslider-first" );
_inputLast.addClass( "ui-rangeslider-last" );
$el.addClass( elClass );
_sliderFirst.appendTo( _sliders );
_sliderLast.appendTo( _sliders );
label.prependTo( $el );
firstHandle.prependTo( _sliderLast );
$.extend( this, {
_inputFirst: _inputFirst,
_inputLast: _inputLast,
_sliderFirst: _sliderFirst,
_sliderLast: _sliderLast,
_targetVal: null,
_sliderTarget: false,
_sliders: _sliders,
_proxy: false
});
this.refresh();
this._on( this.element.find( "input.ui-slider-input" ), {
"slidebeforestart": "_slidebeforestart",
"slidestop": "_slidestop",
"slidedrag": "_slidedrag",
"slidebeforechange": "_change",
"blur": "_change",
"keyup": "_change"
});
this._on({
"mousedown":"_change"
});
this._on( this.element.closest( "form" ), {
"reset":"_handleReset"
});
this._on( firstHandle, {
"vmousedown": "_dragFirstHandle"
});
},
_handleReset: function(){
var self = this;
//we must wait for the stack to unwind before updateing other wise sliders will not have updated yet
setTimeout( function(){
self._updateHighlight();
},0);
},
_dragFirstHandle: function( event ) {
//if the first handle is dragged send the event to the first slider
$.data( this._inputFirst.get(0), "mobileSlider" ).dragging = true;
$.data( this._inputFirst.get(0), "mobileSlider" ).refresh( event );
return false;
},
_slidedrag: function( event ) {
var first = $( event.target ).is( this._inputFirst ),
otherSlider = ( first ) ? this._inputLast : this._inputFirst;
this._sliderTarget = false;
//if the drag was initiated on an extreme and the other handle is focused send the events to
//the closest handle
if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) {
$.data( otherSlider.get(0), "mobileSlider" ).dragging = true;
$.data( otherSlider.get(0), "mobileSlider" ).refresh( event );
return false;
}
},
_slidestop: function( event ) {
var first = $( event.target ).is( this._inputFirst );
this._proxy = false;
//this stops dragging of the handle and brings the active track to the front
//this makes clicks on the track go the the last handle used
this.element.find( "input" ).trigger( "vmouseup" );
this._sliderFirst.css( "z-index", first ? 1 : "" );
},
_slidebeforestart: function( event ) {
this._sliderTarget = false;
//if the track is the target remember this and the original value
if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) {
this._sliderTarget = true;
this._targetVal = $( event.target ).val();
}
},
_setOption: function( options ) {
this._superApply( options );
this.refresh();
},
refresh: function() {
var $el = this.element,
o = this.options;
$el.find( "input" ).slider({
theme: o.theme,
trackTheme: o.trackTheme,
disabled: o.disabled,
mini: o.mini,
highlight: o.highlight
}).slider( "refresh" );
this._updateHighlight();
},
_change: function( event ) {
if ( event.type === "keyup" ) {
this._updateHighlight();
return false;
}
var self = this,
min = parseFloat( this._inputFirst.val(), 10 ),
max = parseFloat( this._inputLast.val(), 10 ),
first = $( event.target ).hasClass( "ui-rangeslider-first" ),
thisSlider = first ? this._inputFirst : this._inputLast,
otherSlider = first ? this._inputLast : this._inputFirst;
if( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ){
thisSlider.blur();
} else if( event.type === "mousedown" ){
return;
}
if ( min > max && !this._sliderTarget ) {
//this prevents min from being greater then max
thisSlider.val( first ? max: min ).slider( "refresh" );
this._trigger( "normalize" );
} else if ( min > max ) {
//this makes it so clicks on the target on either extreme go to the closest handle
thisSlider.val( this._targetVal ).slider( "refresh" );
//You must wait for the stack to unwind so first slider is updated before updating second
setTimeout( function() {
otherSlider.val( first ? min: max ).slider( "refresh" );
$.data( otherSlider.get(0), "mobileSlider" ).handle.focus();
self._sliderFirst.css( "z-index", first ? "" : 1 );
self._trigger( "normalize" );
}, 0 );
this._proxy = ( first ) ? "first" : "last";
}
//fixes issue where when both _sliders are at min they cannot be adjusted
if ( min === max ) {
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", 1 );
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", 0 );
} else {
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
}
this._updateHighlight();
if ( min >= max ) {
return false;
}
},
_updateHighlight: function() {
var min = parseInt( $.data( this._inputFirst.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
max = parseInt( $.data( this._inputLast.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
width = (max - min);
this.element.find( ".ui-slider-bg" ).css({
"margin-left": min + "%",
"width": width + "%"
});
},
_destroy: function() {
this.element.removeClass( "ui-rangeslider ui-mini" ).find( "label" ).show();
this._inputFirst.after( this._sliderFirst );
this._inputLast.after( this._sliderLast );
this._sliders.remove();
this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" );
}
});
$.widget( "mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset );
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.rangeslider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.selectmenu", $.mobile.widget, $.extend( {
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: false,
corners: true,
shadow: true,
iconshadow: true,
overlayTheme: "a",
dividerTheme: "b",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "select:not( :jqmData(role='slider') )",
mini: false
},
_button: function() {
return $( "<div/>" );
},
_setDisabled: function( value ) {
this.element.attr( "disabled", value );
this.button.attr( "aria-disabled", value );
return this._setOption( "disabled", value );
},
_focusButton : function() {
var self = this;
setTimeout( function() {
self.button.focus();
}, 40);
},
_selectOptions: function() {
return this.select.find( "option" );
},
// setup items that are generally necessary for select menu extension
_preExtension: function() {
var classes = "";
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
classes = " ui-btn-left";
}
if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
classes = " ui-btn-right";
}
this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" );
this.selectID = this.select.attr( "id" );
this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
this.isMultiple = this.select[ 0 ].multiple;
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
}
},
_destroy: function() {
var wrapper = this.element.parents( ".ui-select" );
if ( wrapper.length > 0 ) {
if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) {
this.element.addClass( wrapper.is( ".ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" );
}
this.element.insertAfter( wrapper );
wrapper.remove();
}
},
_create: function() {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger( "beforeCreate" );
this.button = this._button();
var self = this,
options = this.options,
inline = options.inline || this.select.jqmData( "inline" ),
mini = options.mini || this.select.jqmData( "mini" ),
iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.insertBefore( this.select )
.buttonMarkup( {
theme: options.theme,
icon: options.icon,
iconpos: iconpos,
inline: inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow,
mini: mini
});
this.setButtonText();
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if ( options.nativeMenu && window.opera && window.opera.version ) {
button.addClass( "ui-select-nativeonly" );
}
// Add counter for multi selects
if ( this.isMultiple ) {
this.buttonCount = $( "<span>" )
.addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
.hide()
.appendTo( button.addClass('ui-li-has-count') );
}
// Disable if specified
if ( options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change(function() {
self.refresh();
if ( !!options.nativeMenu ) {
this.blur();
}
});
this._handleFormReset();
this.build();
},
build: function() {
var self = this;
this.select
.appendTo( self.button )
.bind( "vmousedown", function() {
// Add active class to button
self.button.addClass( $.mobile.activeBtnClass );
})
.bind( "focus", function() {
self.button.addClass( $.mobile.focusClass );
})
.bind( "blur", function() {
self.button.removeClass( $.mobile.focusClass );
})
.bind( "focus vmouseover", function() {
self.button.trigger( "vmouseover" );
})
.bind( "vmousemove", function() {
// Remove active class on scroll/touchmove
self.button.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur vmouseout", function() {
self.button.trigger( "vmouseout" )
.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur", function() {
self.button.removeClass( "ui-btn-down-" + self.options.theme );
});
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
self.button.bind( "vmousedown", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.label.bind( "click focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.select.bind( "focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.button.bind( "mouseup", function() {
if ( self.options.preventFocusZoom ) {
setTimeout(function() {
$.mobile.zoom.enable( true );
}, 0 );
}
});
self.select.bind( "blur", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
},
selected: function() {
return this._selectOptions().filter( ":selected" );
},
selectedIndices: function() {
var self = this;
return this.selected().map(function() {
return self._selectOptions().index( this );
}).get();
},
setButtonText: function() {
var self = this,
selected = this.selected(),
text = this.placeholder,
span = $( document.createElement( "span" ) );
this.button.find( ".ui-btn-text" ).html(function() {
if ( selected.length ) {
text = selected.map(function() {
return $( this ).text();
}).get().join( ", " );
} else {
text = self.placeholder;
}
// TODO possibly aggregate multiple select option classes
return span.text( text )
.addClass( self.select.attr( "class" ) )
.addClass( selected.attr( "class" ) );
});
},
setButtonCount: function() {
var selected = this.selected();
// multiple count inside button
if ( this.isMultiple ) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
}
},
_reset: function() {
this.refresh();
},
refresh: function() {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function() {
this._setDisabled( true );
this.button.addClass( "ui-disabled" );
},
enable: function() {
this._setDisabled( false );
this.button.removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
function fitSegmentInsideSegment( winSize, segSize, offset, desired ) {
var ret = desired;
if ( winSize < segSize ) {
// Center segment if it's bigger than the window
ret = offset + ( winSize - segSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
ret = Math.min( Math.max( offset, desired - segSize / 2 ), offset + winSize - segSize );
}
return ret;
}
function windowCoords() {
var $win = $.mobile.window;
return {
x: $win.scrollLeft(),
y: $win.scrollTop(),
cx: ( window.innerWidth || $win.width() ),
cy: ( window.innerHeight || $win.height() )
};
}
$.widget( "mobile.popup", $.mobile.widget, {
options: {
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
initSelector: ":jqmData(role='popup')",
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_eatEventAndClose: function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
if ( this.options.dismissible ) {
this.close();
}
return false;
},
// Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height
_resizeScreen: function() {
var popupHeight = this._ui.container.outerHeight( true );
this._ui.screen.removeAttr( "style" );
if ( popupHeight > this._ui.screen.height() ) {
this._ui.screen.height( popupHeight );
}
},
_handleWindowKeyUp: function( e ) {
if ( this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE ) {
return this._eatEventAndClose( e );
}
},
_expectResizeEvent: function() {
var winCoords = windowCoords();
if ( this._resizeData ) {
if ( winCoords.x === this._resizeData.winCoords.x &&
winCoords.y === this._resizeData.winCoords.y &&
winCoords.cx === this._resizeData.winCoords.cx &&
winCoords.cy === this._resizeData.winCoords.cy ) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout( this._resizeData.timeoutId );
}
}
this._resizeData = {
timeoutId: setTimeout( $.proxy( this, "_resizeTimeout" ), 200 ),
winCoords: winCoords
};
return true;
},
_resizeTimeout: function() {
if ( this._isOpen ) {
if ( !this._expectResizeEvent() ) {
if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass( "ui-popup-hidden" );
this.reposition( { positionTo: "window" } );
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_ignoreResizeEvents: function() {
var self = this;
if ( this._ignoreResizeTo ) {
clearTimeout( this._ignoreResizeTo );
}
this._ignoreResizeTo = setTimeout( function() { self._ignoreResizeTo = 0; }, 1000 );
},
_handleWindowResize: function( e ) {
if ( this._isOpen && this._ignoreResizeTo === 0 ) {
if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
!this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
}
}
},
_handleWindowOrientationchange: function( e ) {
if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function( e ) {
var tgt = e.target, $tgt, ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( tgt !== ui.container[ 0 ] ) {
$tgt = $( e.target );
if ( 0 === $tgt.parents().filter( ui.container[ 0 ] ).length ) {
$( document.activeElement ).one( "focus", function( e ) {
$tgt.blur();
});
ui.focusElement.focus();
e.preventDefault();
e.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = $tgt;
}
}
this._ignoreResizeEvents();
},
_create: function() {
var ui = {
screen: $( "<div class='ui-screen-hidden ui-popup-screen'></div>" ),
placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
container: $( "<div class='ui-popup-container ui-popup-hidden'></div>" )
},
thisPage = this.element.closest( ".ui-page" ),
myId = this.element.attr( "id" ),
o = this.options,
key, value;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
o.history = o.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
if ( thisPage.length === 0 ) {
thisPage = $( "body" );
}
// define the container for navigation event bindings
// TODO this would be nice at the the mobile widget level
o.container = o.container || $.mobile.pageContainer || thisPage;
// Apply the proto
thisPage.append( ui.screen );
ui.container.insertAfter( ui.screen );
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter( this.element );
if ( myId ) {
ui.screen.attr( "id", myId + "-screen" );
ui.container.attr( "id", myId + "-popup" );
ui.placeholder.html( "<!-- placeholder for " + myId + " -->" );
}
ui.container.append( this.element );
ui.focusElement = ui.container;
// Add class to popup element
this.element.addClass( "ui-popup" );
// Define instance variables
$.extend( this, {
_scrollTop: 0,
_page: thisPage,
_ui: ui,
_fallbackTransition: "",
_currentTransition: false,
_prereqs: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
// This duplicates the code from the various option setters below for
// better performance. It must be kept in sync with those setters.
this._applyTheme( this.element, o.theme, "body" );
this._applyTheme( this._ui.screen, o.overlayTheme, "overlay" );
this._applyTransition( o.transition );
this.element
.toggleClass( "ui-overlay-shadow", o.shadow )
.toggleClass( "ui-corner-all", o.corners );
this._setTolerance( o.tolerance );
ui.screen.bind( "vclick", $.proxy( this, "_eatEventAndClose" ) );
this._on( $.mobile.window, {
orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
resize: $.proxy( this, "_handleWindowResize" ),
keyup: $.proxy( this, "_handleWindowKeyUp" )
});
this._on( $.mobile.document, {
focusin: $.proxy( this, "_handleDocumentFocusIn" )
});
},
_applyTheme: function( dst, theme, prefix ) {
var classes = ( dst.attr( "class" ) || "").split( " " ),
alreadyAdded = true,
currentTheme = null,
matches,
themeStr = String( theme );
while ( classes.length > 0 ) {
currentTheme = classes.pop();
matches = ( new RegExp( "^ui-" + prefix + "-([a-z])$" ) ).exec( currentTheme );
if ( matches && matches.length > 1 ) {
currentTheme = matches[ 1 ];
break;
} else {
currentTheme = null;
}
}
if ( theme !== currentTheme ) {
dst.removeClass( "ui-" + prefix + "-" + currentTheme );
if ( ! ( theme === null || theme === "none" ) ) {
dst.addClass( "ui-" + prefix + "-" + themeStr );
}
}
},
_setTheme: function( value ) {
this._applyTheme( this.element, value, "body" );
},
_setOverlayTheme: function( value ) {
this._applyTheme( this._ui.screen, value, "overlay" );
if ( this._isOpen ) {
this._ui.screen.addClass( "in" );
}
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-overlay-shadow", value );
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_applyTransition: function( value ) {
this._ui.container.removeClass( this._fallbackTransition );
if ( value && value !== "none" ) {
this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
if ( this._fallbackTransition === "none" ) {
this._fallbackTransition = "";
}
this._ui.container.addClass( this._fallbackTransition );
}
},
_setTransition: function( value ) {
if ( !this._currentTransition ) {
this._applyTransition( value );
}
},
_setTolerance: function( value ) {
var tol = { t: 30, r: 15, b: 30, l: 15 };
if ( value !== undefined ) {
var ar = String( value ).split( "," );
$.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
switch( ar.length ) {
// All values are to be the same
case 1:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.b = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.r = ar[ 1 ];
}
if ( !isNaN( ar[ 2 ] ) ) {
tol.b = ar[ 2 ];
}
if ( !isNaN( ar[ 3 ] ) ) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
},
_setOption: function( key, value ) {
var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
this._super( key, value );
},
// Try and center the overlay over the given coordinates
_placementCoords: function( desired ) {
// rectangle within which the popup must fit
var
winCoords = windowCoords(),
rc = {
x: this._tolerance.l,
y: winCoords.y + this._tolerance.t,
cx: winCoords.cx - this._tolerance.l - this._tolerance.r,
cy: winCoords.cy - this._tolerance.t - this._tolerance.b
},
menuSize, ret;
// Clamp the width of the menu before grabbing its size
this._ui.container.css( "max-width", rc.cx );
menuSize = {
cx: this._ui.container.outerWidth( true ),
cy: this._ui.container.outerHeight( true )
};
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is too large.
ret = {
x: fitSegmentInsideSegment( rc.cx, menuSize.cx, rc.x, desired.x ),
y: fitSegmentInsideSegment( rc.cy, menuSize.cy, rc.y, desired.y )
};
// Make sure the top of the menu is visible
ret.y = Math.max( 0, ret.y );
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
// fix for $.mobile.document.height() bug in core 1.7.2.
var docEl = document.documentElement, docBody = document.body,
docHeight = Math.max( docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight );
ret.y -= Math.min( ret.y, Math.max( 0, ret.y + menuSize.cy - docHeight ) );
return { left: ret.x, top: ret.y };
},
_createPrereqs: function( screenPrereq, containerPrereq, whenDone ) {
var self = this, prereqs;
// It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in
// the closure of the functions which call the callbacks passed in. The comparison between the local variable and
// self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called
// next time an animation completes, even if that's not the animation whose end the function was supposed to catch
// (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for
// that animation anymore, but the handler remains attached, so it is called the next time the popup is opened
// - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that
// callbacks triggered by a stale .animationComplete will be ignored.
prereqs = {
screen: $.Deferred(),
container: $.Deferred()
};
prereqs.screen.then( function() {
if ( prereqs === self._prereqs ) {
screenPrereq();
}
});
prereqs.container.then( function() {
if ( prereqs === self._prereqs ) {
containerPrereq();
}
});
$.when( prereqs.screen, prereqs.container ).done( function() {
if ( prereqs === self._prereqs ) {
self._prereqs = null;
whenDone();
}
});
self._prereqs = prereqs;
},
_animate: function( args ) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass( args.classToRemove )
.addClass( args.screenClassToAdd );
args.prereqs.screen.resolve();
if ( args.transition && args.transition !== "none" ) {
if ( args.applyTransition ) {
this._applyTransition( args.transition );
}
if ( this._fallbackTransition ) {
this._ui.container
.animationComplete( $.proxy( args.prereqs.container, "resolve" ) )
.addClass( args.containerClassToAdd )
.removeClass( args.classToRemove );
return;
}
}
this._ui.container.removeClass( args.classToRemove );
args.prereqs.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function( o ) {
var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo;
// Establish which element will serve as the reference
if ( pTo && pTo !== "origin" ) {
if ( pTo === "window" ) {
x = winCoords.cx / 2 + winCoords.x;
y = winCoords.cy / 2 + winCoords.y;
} else {
try {
dst = $( pTo );
} catch( e ) {
dst = null;
}
if ( dst ) {
dst.filter( ":visible" );
if ( dst.length === 0 ) {
dst = null;
}
}
}
}
// If an element was found, center over it
if ( dst ) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ( $.type( x ) !== "number" || isNaN( x ) ) {
x = winCoords.cx / 2 + winCoords.x;
}
if ( $.type( y ) !== "number" || isNaN( y ) ) {
y = winCoords.cy / 2 + winCoords.y;
}
return { x: x, y: y };
},
_reposition: function( o ) {
// We only care about position-related parameters for repositioning
o = { x: o.x, y: o.y, positionTo: o.positionTo };
this._trigger( "beforeposition", undefined, o );
this._ui.container.offset( this._placementCoords( this._desiredCoords( o ) ) );
},
reposition: function( o ) {
if ( this._isOpen ) {
this._reposition( o );
}
},
_openPrereqsComplete: function() {
this._ui.container.addClass( "ui-popup-active" );
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr( "tabindex", "0" ).focus();
this._ignoreResizeEvents();
this._trigger( "afteropen" );
},
_open: function( options ) {
var o = $.extend( {}, this.options, options ),
// TODO move blacklist to private method
androidBlacklist = ( function() {
var w = window,
ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf( "Chrome" ) > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.noop,
$.noop,
$.proxy( this, "_openPrereqsComplete" ) );
this._currentTransition = o.transition;
this._applyTransition( o.transition );
if ( !this.options.theme ) {
this._setTheme( this._page.jqmData( "theme" ) || $.mobile.getInheritedTheme( this._page, "c" ) );
}
this._ui.screen.removeClass( "ui-screen-hidden" );
this._ui.container.removeClass( "ui-popup-hidden" );
// Give applications a chance to modify the contents of the container before it appears
this._reposition( o );
if ( this.options.overlayTheme && androidBlacklist ) {
/* TODO:
The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed
above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain
types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser:
https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
}
this._animate({
additionalCondition: true,
transition: o.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prereqs: this._prereqs
});
},
_closePrereqScreen: function() {
this._ui.screen
.removeClass( "out" )
.addClass( "ui-screen-hidden" );
},
_closePrereqContainer: function() {
this._ui.container
.removeClass( "reverse out" )
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
},
_closePrereqsDone: function() {
var container = this._ui.container;
container.removeAttr( "tabindex" );
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// Blur elements inside the container, including the container
$( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur();
// alert users that the popup is closed
this._trigger( "afterclose" );
},
_close: function( immediate ) {
this._ui.container.removeClass( "ui-popup-active" );
this._page.removeClass( "ui-popup-open" );
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.proxy( this, "_closePrereqScreen" ),
$.proxy( this, "_closePrereqContainer" ),
$.proxy( this, "_closePrereqsDone" ) );
this._animate( {
additionalCondition: this._ui.screen.hasClass( "in" ),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prereqs: this._prereqs
});
},
_unenhance: function() {
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setTheme( "none" );
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter( this._ui.placeholder )
.removeClass( "ui-popup ui-overlay-shadow ui-corner-all" );
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function() {
if ( $.mobile.popup.active === this ) {
this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
this.close();
} else {
this._unenhance();
}
},
_closePopup: function( e, data ) {
var parsedDst, toUrl, o = this.options, immediate = false;
// restore location on screen
window.scrollTo( 0, this._scrollTop );
if ( e && e.type === "pagebeforechange" && data ) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if ( typeof data.toPage === "string" ) {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData( "url" );
}
parsedDst = $.mobile.path.parseUrl( parsedDst );
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
// Going to a different page - close immediately
immediate = true;
} else {
e.preventDefault();
}
}
// remove nav bindings
o.container.unbind( o.closeEvents );
// unbind click handlers added when history is disabled
this.element.undelegate( o.closeLinkSelector, o.closeLinkEvents );
this._close( immediate );
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function() {
this.options.container
.one( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function( options ) {
var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory;
// make sure open is idempotent
if( $.mobile.popup.active ) {
return;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = $.mobile.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if( !( opts.history ) ) {
self._open( options );
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate( opts.closeLinkSelector, opts.closeLinkEvents, function( e ) {
self.close();
e.preventDefault();
});
return;
}
// cache some values for min/readability
urlHistory = $.mobile.urlHistory;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = activePage.is( ".ui-dialog" );
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if ( hasHash ) {
self._open( options );
self._bindContainerClose();
return;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ){
url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
$(window).one( "beforenavigate", function( e ) {
e.preventDefault();
self._open( options );
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate( url, {role: "dialog"} );
},
close: function() {
// make sure close is idempotent
if( $.mobile.popup.active !== this ) {
return;
}
this._scrollTop = $.mobile.window.scrollTop();
if( this.options.history && this.urlAltered ) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function( $link ) {
var closestPage = $link.closest( ":jqmData(role='page')" ),
scope = ( ( closestPage.length === 0 ) ? $( "body" ) : closestPage ),
// NOTE make sure to get only the hash, ie7 (wp7) return the absolute href
// in this case ruining the element selection
popup = $( $.mobile.path.parseUrl($link.attr( "href" )).hash, scope[0] ),
offset;
if ( popup.data( "mobile-popup" ) ) {
offset = $link.offset();
popup.popup( "open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData( "transition" ),
positionTo: $link.jqmData( "position-to" )
});
}
//remove after delay
setTimeout( function() {
// Check if we are in a listview
var $parent = $link.parent().parent();
if ($parent.hasClass("ui-li")) {
$link = $parent.parent();
}
$link.removeClass( $.mobile.activeBtnClass );
}, 300 );
};
// TODO move inside _create
$.mobile.document.bind( "pagebeforechange", function( e, data ) {
if ( data.options.role === "popup" ) {
$.mobile.popup.handleLink( data.options.link );
e.preventDefault();
}
});
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.popup.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
/*
* custom "selectmenu" plugin
*/
(function( $, undefined ) {
var extendSelect = function( widget ) {
var select = widget.select,
origDestroy = widget._destroy,
selectID = widget.selectID,
prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ),
popupID = prefix + "-listbox",
dialogID = prefix + "-dialog",
label = widget.label,
thisPage = widget.select.closest( ".ui-page" ),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>"+
"</div>"+
"<div data-" + $.mobile.ns + "role='content'></div>"+
"</div>" ),
listbox = $( "<div id='" + popupID + "' class='ui-selectmenu'>" ).insertAfter( widget.select ).popup( { theme: widget.options.overlayTheme } ),
list = $( "<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr( "data-" + $.mobile.ns + "theme", widget.options.theme )
.attr( "data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme )
.appendTo( listbox ),
header = $( "<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo( listbox ),
headerTitle = $( "<h1>", {
"class": "ui-title"
}).appendTo( header ),
menuPageContent,
menuPageClose,
headerClose;
if ( widget.isMultiple ) {
headerClose = $( "<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
}
$.extend( widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
popupID: popupID,
dialogID: dialogID,
thisPage: thisPage,
menuPage: menuPage,
label: label,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function() {
var self = this,
escapeId = function( id ) {
return id.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" );
};
// Create list from select, update state
self.refresh();
if ( self._origTabIndex === undefined ) {
// Map undefined to false, because self._origTabIndex === undefined
// indicates that we have not yet checked whether the select has
// originally had a tabindex attribute, whereas false indicates that
// we have checked the select for such an attribute, and have found
// none present.
self._origTabIndex = ( self.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : self.select.attr( "tabindex" );
}
self.select.attr( "tabindex", "-1" ).focus(function() {
$( this ).blur();
self.button.focus();
});
// Button events
self.button.bind( "vclick keydown" , function( event ) {
if ( self.options.disabled || self.isOpen ) {
return;
}
if (event.type === "vclick" ||
event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE)) {
self._decideFormat();
if ( self.menuType === "overlay" ) {
self.button.attr( "href", "#" + escapeId( self.popupID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" );
} else {
self.button.attr( "href", "#" + escapeId( self.dialogID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" );
}
self.isOpen = true;
// Do not prevent default, so the navigation may have a chance to actually open the chosen format
}
});
// Events for list items
self.list.attr( "role", "listbox" )
.bind( "focusin", function( e ) {
$( e.target )
.attr( "tabindex", "0" )
.trigger( "vmouseover" );
})
.bind( "focusout", function( e ) {
$( e.target )
.attr( "tabindex", "-1" )
.trigger( "vmouseout" );
})
.delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
option = self._selectOptions().eq( newIndex )[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if ( self.isMultiple ) {
$( this ).find( ".ui-icon" )
.toggleClass( "ui-icon-checkbox-on", option.selected )
.toggleClass( "ui-icon-checkbox-off", !option.selected );
}
// trigger change if value changed
if ( self.isMultiple || oldIndex !== newIndex ) {
self.select.trigger( "change" );
}
// hide custom select for single selects only - otherwise focus clicked item
// We need to grab the clicked item the hard way, because the list may have been rebuilt
if ( self.isMultiple ) {
self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
else {
self.close();
}
event.preventDefault();
})
.keydown(function( event ) { //keyboard events for menu items
var target = $( event.target ),
li = target.closest( "li" ),
prev, next;
// switch logic based on which key was pressed
switch ( event.keyCode ) {
// up or left arrow keys
case 38:
prev = li.prev().not( ".ui-selectmenu-placeholder" );
if ( prev.is( ".ui-li-divider" ) ) {
prev = prev.prev();
}
// if there's a previous option, focus it
if ( prev.length ) {
target
.blur()
.attr( "tabindex", "-1" );
prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// down or right arrow keys
case 40:
next = li.next();
if ( next.is( ".ui-li-divider" ) ) {
next = next.next();
}
// if there's a next option, focus it
if ( next.length ) {
target
.blur()
.attr( "tabindex", "-1" );
next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger( "click" );
return false;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind( "pagehide", function() {
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call( self.thisPage );
});
// Events on the popup
self.listbox.bind( "popupafterclose", function( event ) {
self.close();
});
// Close button on small overlays
if ( self.isMultiple ) {
self.headerClose.click(function() {
if ( self.menuType === "overlay" ) {
self.close();
return false;
}
});
}
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents( this.menuPage );
},
_isRebuildRequired: function() {
var list = this.list.find( "li" ),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
selected: function() {
return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" );
},
refresh: function( forceRebuild , foo ) {
var self = this,
select = this.element,
isMultiple = this.isMultiple,
indicies;
if ( forceRebuild || this._isRebuildRequired() ) {
self._buildList();
}
indicies = this.selectedIndices();
self.setButtonText();
self.setButtonCount();
self.list.find( "li:not(.ui-li-divider)" )
.removeClass( $.mobile.activeBtnClass )
.attr( "aria-selected", false )
.each(function( i ) {
if ( $.inArray( i, indicies ) > -1 ) {
var item = $( this );
// Aria selected attr
item.attr( "aria-selected", true );
// Multiple selects: add the "on" checkbox state to the icon
if ( self.isMultiple ) {
item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
} else {
if ( item.is( ".ui-selectmenu-placeholder" ) ) {
item.next().addClass( $.mobile.activeBtnClass );
} else {
item.addClass( $.mobile.activeBtnClass );
}
}
}
});
},
close: function() {
if ( this.options.disabled || !this.isOpen ) {
return;
}
var self = this;
if ( self.menuType === "page" ) {
self.menuPage.dialog( "close" );
self.list.appendTo( self.listbox );
} else {
self.listbox.popup( "close" );
}
self._focusButton();
// allow the dialog to be closed again
self.isOpen = false;
},
open: function() {
this.button.click();
},
_decideFormat: function() {
var self = this,
$window = $.mobile.window,
selfListParent = self.list.parent(),
menuHeight = selfListParent.outerHeight(),
menuWidth = selfListParent.outerWidth(),
activePage = $( "." + $.mobile.activePageClass ),
scrollTop = $window.scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = $window.height(),
screenWidth = $window.width();
function focusMenuItem() {
var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
if ( selector.length === 0 ) {
selector = self.list.find( "li.ui-btn:not( :jqmData(placeholder='true') ) a" );
}
selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
}
if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
self.menuPage.appendTo( $.mobile.pageContainer ).page();
self.menuPageContent = menuPage.find( ".ui-content" );
self.menuPageClose = menuPage.find( ".ui-header a" );
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind( "pagehide.remove" );
//for WebOS/Opera Mini (set lastscroll using button offset)
if ( scrollTop === 0 && btnOffset > screenHeight ) {
self.thisPage.one( "pagehide", function() {
$( this ).jqmData( "lastScroll", btnOffset );
});
}
self.menuPage
.one( "pageshow", function() {
focusMenuItem();
})
.one( "pagehide", function() {
self.close();
});
self.menuType = "page";
self.menuPageContent.append( self.list );
self.menuPage.find("div .ui-title").text(self.label.text());
} else {
self.menuType = "overlay";
self.listbox.one( "popupafteropen", focusMenuItem );
}
},
_buildList: function() {
var self = this,
o = this.options,
placeholder = this.placeholder,
needPlaceholder = true,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
var $options = self.select.find( "option" ),
numOptions = $options.length,
select = this.select[ 0 ],
dataPrefix = 'data-' + $.mobile.ns,
dataIndexAttr = dataPrefix + 'option-index',
dataIconAttr = dataPrefix + 'icon',
dataRoleAttr = dataPrefix + 'role',
dataPlaceholderAttr = dataPrefix + 'placeholder',
fragment = document.createDocumentFragment(),
isPlaceholderItem = false,
optGroup;
for (var i = 0; i < numOptions;i++, isPlaceholderItem = false) {
var option = $options[i],
$option = $( option ),
parent = option.parentNode,
text = $option.text(),
anchor = document.createElement( 'a' ),
classes = [];
anchor.setAttribute( 'href', '#' );
anchor.appendChild( document.createTextNode( text ) );
// Are we inside an optgroup?
if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) {
var optLabel = parent.getAttribute( 'label' );
if ( optLabel !== optGroup ) {
var divider = document.createElement( 'li' );
divider.setAttribute( dataRoleAttr, 'list-divider' );
divider.setAttribute( 'role', 'option' );
divider.setAttribute( 'tabindex', '-1' );
divider.appendChild( document.createTextNode( optLabel ) );
fragment.appendChild( divider );
optGroup = optLabel;
}
}
if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) {
needPlaceholder = false;
isPlaceholderItem = true;
// If we have identified a placeholder, record the fact that it was
// us who have added the placeholder to the option and mark it
// retroactively in the select as well
if ( null === option.getAttribute( dataPlaceholderAttr ) ) {
this._removePlaceholderAttr = true;
}
option.setAttribute( dataPlaceholderAttr, true );
if ( o.hidePlaceholderMenuItems ) {
classes.push( "ui-selectmenu-placeholder" );
}
if ( placeholder !== text ) {
placeholder = self.placeholder = text;
}
}
var item = document.createElement('li');
if ( option.disabled ) {
classes.push( "ui-disabled" );
item.setAttribute('aria-disabled',true);
}
item.setAttribute( dataIndexAttr,i );
item.setAttribute( dataIconAttr, dataIcon );
if ( isPlaceholderItem ) {
item.setAttribute( dataPlaceholderAttr, true );
}
item.className = classes.join( " " );
item.setAttribute( 'role', 'option' );
anchor.setAttribute( 'tabindex', '-1' );
item.appendChild( anchor );
fragment.appendChild( item );
}
self.list[0].appendChild( fragment );
// Hide header if it's not a multiselect and there's no placeholder
if ( !this.isMultiple && !placeholder.length ) {
this.header.hide();
} else {
this.headerTitle.text( this.placeholder );
}
// Now populated, create listview
self.list.listview();
},
_button: function() {
return $( "<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
},
_destroy: function() {
this.close();
// Restore the tabindex attribute to its original value
if ( this._origTabIndex !== undefined ) {
if ( this._origTabIndex !== false ) {
this.select.attr( "tabindex", this._origTabIndex );
} else {
this.select.removeAttr( "tabindex" );
}
}
// Remove the placeholder attribute if we were the ones to add it
if ( this._removePlaceholderAttr ) {
this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" );
}
// Remove the popup
this.listbox.remove();
// Remove the dialog
this.menuPage.remove();
// Chain up
origDestroy.apply( this, arguments );
}
});
};
// issue #3894 - core doesn't trigger events on disabled delegates
$.mobile.document.bind( "selectmenubeforecreate", function( event ) {
var selectmenuWidget = $( event.target ).data( "mobile-selectmenu" );
if ( !selectmenuWidget.options.nativeMenu &&
selectmenuWidget.element.parents( ":jqmData(role='popup')" ).length === 0 ) {
extendSelect( selectmenuWidget );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.controlgroup", $.mobile.widget, $.extend( {
options: {
shadow: false,
corners: true,
excludeInvisible: true,
type: "vertical",
mini: false,
initSelector: ":jqmData(role='controlgroup')"
},
_create: function() {
var $el = this.element,
ui = {
inner: $( "<div class='ui-controlgroup-controls'></div>" ),
legend: $( "<div role='heading' class='ui-controlgroup-label'></div>" )
},
grouplegend = $el.children( "legend" ),
self = this;
// Apply the proto
$el.wrapInner( ui.inner );
if ( grouplegend.length ) {
ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
}
$el.addClass( "ui-corner-all ui-controlgroup" );
$.extend( this, {
_initialRefresh: true
});
$.each( this.options, function( key, value ) {
// Cause initial options to be applied by their handler by temporarily setting the option to undefined
// - the handler then sets it to the initial value
self.options[ key ] = undefined;
self._setOption( key, value, true );
});
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
this._super( key, value );
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
},
_setType: function( value ) {
this.element
.removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
.addClass( "ui-controlgroup-" + value );
this.refresh();
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-shadow", value );
},
_setMini: function( value ) {
this.element.toggleClass( "ui-mini", value );
},
container: function() {
return this.element.children( ".ui-controlgroup-controls" );
},
refresh: function() {
var els = this.element.find( ".ui-btn" ).not( ".ui-slider-handle" ),
create = this._initialRefresh;
if ( $.mobile.checkboxradio ) {
this.element.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" );
}
this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create );
this._initialRefresh = false;
}
}, $.mobile.behaviors.addFirstLastClasses ) );
// TODO: Implement a mechanism to allow widgets to become enhanced in the
// correct order when their correct enhancement depends on other widgets in
// the page being correctly enhanced already.
//
// For now, we wait until dom-ready to attach the controlgroup's enhancement
// hook, because by that time, all the other widgets' enhancement hooks should
// already be in place, ensuring that all widgets that need to be grouped will
// already have been enhanced by the time the controlgroup is created.
$( function() {
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
});
});
})(jQuery);
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
//links within content areas, tests included with page
$( e.target )
.find( "a" )
.jqmEnhanceable()
.filter( ":jqmData(rel='popup')[href][href!='']" )
.each( function() {
// Accessibility info for popups
var e = this,
href = $( this ).attr( "href" ),
idref = href.substring( 1 );
e.setAttribute( "aria-haspopup", true );
e.setAttribute( "aria-owns", idref );
e.setAttribute( "aria-expanded", false );
$( document )
.on( "popupafteropen", href, function() {
e.setAttribute( "aria-expanded", true );
})
.on( "popupafterclose", href, function() {
e.setAttribute( "aria-expanded", false );
});
})
.end()
.not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
.addClass( "ui-link" );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
options: {
visibleOnPageShow: true,
disablePageZoom: true,
transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
fullscreen: false,
tapToggle: true,
tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
hideDuringFocus: "input, textarea, select",
updatePagePadding: true,
trackPersistentToolbars: true,
// Browser detection! Weeee, here we go...
// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
// The following function serves to rule out some popular browsers with known fixed-positioning issues
// This is a plugin option like any other, so feel free to improve or overwrite it
supportBlacklist: function() {
return !$.support.fixedPosition;
},
initSelector: ":jqmData(position='fixed')"
},
_create: function() {
var self = this,
o = self.options,
$el = self.element,
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
$page = $el.closest( ".ui-page" );
// Feature detecting support for
if ( o.supportBlacklist() ) {
self.destroy();
return;
}
$el.addClass( "ui-"+ tbtype +"-fixed" );
// "fullscreen" overlay positioning
if ( o.fullscreen ) {
$el.addClass( "ui-"+ tbtype +"-fullscreen" );
$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
}
// If not fullscreen, add class to page to set top or bottom padding
else{
$page.addClass( "ui-page-" + tbtype + "-fixed" );
}
$.extend( this, {
_thisPage: null
});
self._addTransitionClass();
self._bindPageEvents();
self._bindToggleHandlers();
},
_addTransitionClass: function() {
var tclass = this.options.transition;
if ( tclass && tclass !== "none" ) {
// use appropriate slide for header or footer
if ( tclass === "slide" ) {
tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
}
this.element.addClass( tclass );
}
},
_bindPageEvents: function() {
this._thisPage = this.element.closest( ".ui-page" );
//page event bindings
// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
this._on( this._thisPage, {
"pagebeforeshow": "_handlePageBeforeShow",
"webkitAnimationStart":"_handleAnimationStart",
"animationstart":"_handleAnimationStart",
"updatelayout": "_handleAnimationStart",
"pageshow": "_handlePageShow",
"pagebeforehide": "_handlePageBeforeHide"
});
},
_handlePageBeforeShow: function() {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.disable( true );
}
if ( !o.visibleOnPageShow ) {
this.hide( true );
}
},
_handleAnimationStart: function() {
if ( this.options.updatePagePadding ) {
this.updatePagePadding( this._thisPage );
}
},
_handlePageShow: function() {
this.updatePagePadding( this._thisPage );
if ( this.options.updatePagePadding ) {
this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
}
},
_handlePageBeforeHide: function( e, ui ) {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.enable( true );
}
if ( o.updatePagePadding ) {
this._off( $.mobile.window, "throttledresize" );
}
if ( o.trackPersistentToolbars ) {
var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();
if ( nextFooter.length || nextHeader.length ) {
nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
ui.nextPage.one( "pageshow", function() {
nextHeader.prependTo( this );
nextFooter.appendTo( this );
});
}
}
},
_visible: true,
// This will set the content element's top or bottom padding equal to the toolbar's height
updatePagePadding: function( tbPage ) {
var $el = this.element,
header = $el.is( ".ui-header" ),
pos = parseFloat( $el.css( header ? "top" : "bottom" ) );
// This behavior only applies to "fixed", not "fullscreen"
if ( this.options.fullscreen ) { return; }
// tbPage argument can be a Page object or an event, if coming from throttled resize.
tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" );
$( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
},
_useTransition: function( notransition ) {
var $win = $.mobile.window,
$el = this.element,
scroll = $win.scrollTop(),
elHeight = $el.height(),
pHeight = $el.closest( ".ui-page" ).height(),
viewportHeight = $.mobile.getScreenHeight(),
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
return !notransition &&
( this.options.transition && this.options.transition !== "none" &&
(
( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
) || this.options.fullscreen
);
},
show: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element;
if ( this._useTransition( notransition ) ) {
$el
.removeClass( "out " + hideClass )
.addClass( "in" )
.animationComplete(function () {
$el.removeClass('in');
});
}
else {
$el.removeClass( hideClass );
}
this._visible = true;
},
hide: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element,
// if it's a slide transition, our new transitions need the reverse class as well to slide outward
outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
if( this._useTransition( notransition ) ) {
$el
.addClass( outclass )
.removeClass( "in" )
.animationComplete(function() {
$el.addClass( hideClass ).removeClass( outclass );
});
}
else {
$el.addClass( hideClass ).removeClass( outclass );
}
this._visible = false;
},
toggle: function() {
this[ this._visible ? "hide" : "show" ]();
},
_bindToggleHandlers: function() {
var self = this,
o = self.options,
$el = self.element,
delayShow, delayHide,
isVisible = true;
// tap toggle
$el.closest( ".ui-page" )
.bind( "vclick", function( e ) {
if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
self.toggle();
}
})
.bind( "focusin focusout", function( e ) {
//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
//and issue #4113 Header and footer change their position after keyboard popup - iOS
//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
//controls causes fixed position, tap-toggle false Header to reveal itself
// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
// by a focusout when a native selects opens and the other way around when it closes.
if ( e.type === "focusout" && !isVisible ) {
isVisible = true;
//wait for the stack to unwind and see if we have jumped to another input
clearTimeout( delayHide );
delayShow = setTimeout( function() {
self.show();
}, 0 );
} else if ( e.type === "focusin" && !!isVisible ) {
//if we have jumped to another input clear the time out to cancel the show.
clearTimeout( delayShow );
isVisible = false;
delayHide = setTimeout( function() {
self.hide();
}, 0 );
}
}
});
},
_destroy: function() {
var $el = this.element,
header = $el.is( ".ui-header" );
$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
$el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
$el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
}
});
//auto self-init widgets
$.mobile.document
.bind( "pagecreate create", function( e ) {
// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
if ( $( e.target ).jqmData( "fullscreen" ) ) {
$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
}
$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
_create: function() {
this._super();
this._workarounds();
},
//check the browser and version and run needed workarounds
_workarounds: function() {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){
os = "ios";
} else if( ua.indexOf( "Android" ) > -1 ){
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if( os === "ios" ) {
//iOS workarounds
self._bindScrollWorkaround();
} else if( os === "android" && wkversion && wkversion < 534 ) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
},
//Utility class for checking header and footer positions relative to viewport
_viewportOffset: function() {
var $el = this.element,
header = $el.is( ".ui-header" ),
offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
if( !header ) {
offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60;
}
return offset;
},
//bind events for _triggerRedraw() function
_bindScrollWorkaround: function() {
var self = this;
//bind to scrollstop and check if the toolbars are correctly positioned
this._on( $.mobile.window, { scrollstop: function() {
var viewportOffset = self._viewportOffset();
//check if the header is visible and if its in the right place
if( viewportOffset > 2 && self._visible) {
self._triggerRedraw();
}
}});
},
//this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
//and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
//the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
//setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
//platforms we scope this with the class ui-android-2x-fix
_bindListThumbWorkaround: function() {
this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" );
},
//this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
//and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
//this also addresses not on fixed toolbars page in docs
//adding 1px of padding to the bottom then removing it causes a "redraw"
//which positions the toolbars correctly (they will always be visually correct)
_triggerRedraw: function() {
var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) );
//trigger page redraw to fix incorrectly positioned fixed elements
$( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" );
//if the padding is reset with out a timeout the reposition will not occure.
//this is independant of JQM the browser seems to need the time to react.
setTimeout( function() {
$( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" );
}, 0 );
},
destroy: function() {
this._super();
//Remove the class we added to the page previously in android 2.x
this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.panel", $.mobile.widget, {
options: {
classes: {
panel: "ui-panel",
panelOpen: "ui-panel-open",
panelClosed: "ui-panel-closed",
panelFixed: "ui-panel-fixed",
panelInner: "ui-panel-inner",
modal: "ui-panel-dismiss",
modalOpen: "ui-panel-dismiss-open",
pagePanel: "ui-page-panel",
pagePanelOpen: "ui-page-panel-open",
contentWrap: "ui-panel-content-wrap",
contentWrapOpen: "ui-panel-content-wrap-open",
contentWrapClosed: "ui-panel-content-wrap-closed",
contentFixedToolbar: "ui-panel-content-fixed-toolbar",
contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open",
contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed",
animate: "ui-panel-animate"
},
animate: true,
theme: "c",
position: "left",
dismissible: true,
display: "reveal", //accepts reveal, push, overlay
initSelector: ":jqmData(role='panel')",
swipeClose: true,
positionFixed: false
},
_panelID: null,
_closeLink: null,
_page: null,
_modal: null,
_panelInner: null,
_wrapper: null,
_fixedToolbar: null,
_create: function() {
var self = this,
$el = self.element,
page = $el.closest( ":jqmData(role='page')" ),
_getPageTheme = function() {
var $theme = $.data( page[0], "mobilePage" ).options.theme,
$pageThemeClass = "ui-body-" + $theme;
return $pageThemeClass;
},
_getPanelInner = function() {
var $panelInner = $el.find( "." + self.options.classes.panelInner );
if ( $panelInner.length === 0 ) {
$panelInner = $el.children().wrapAll( '<div class="' + self.options.classes.panelInner + '" />' ).parent();
}
return $panelInner;
},
_getWrapper = function() {
var $wrapper = page.find( "." + self.options.classes.contentWrap );
if ( $wrapper.length === 0 ) {
$wrapper = page.children( ".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))" ).wrapAll( '<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />' ).parent();
if ( $.support.cssTransform3d && !!self.options.animate ) {
$wrapper.addClass( self.options.classes.animate );
}
}
return $wrapper;
},
_getFixedToolbar = function() {
var $fixedToolbar = page.find( "." + self.options.classes.contentFixedToolbar );
if ( $fixedToolbar.length === 0 ) {
$fixedToolbar = page.find( ".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')" ).addClass( self.options.classes.contentFixedToolbar );
if ( $.support.cssTransform3d && !!self.options.animate ) {
$fixedToolbar.addClass( self.options.classes.animate );
}
}
return $fixedToolbar;
};
// expose some private props to other methods
$.extend( this, {
_panelID: $el.attr( "id" ),
_closeLink: $el.find( ":jqmData(rel='close')" ),
_page: $el.closest( ":jqmData(role='page')" ),
_pageTheme: _getPageTheme(),
_panelInner: _getPanelInner(),
_wrapper: _getWrapper(),
_fixedToolbar: _getFixedToolbar()
});
self._addPanelClasses();
self._wrapper.addClass( this.options.classes.contentWrapClosed );
self._fixedToolbar.addClass( this.options.classes.contentFixedToolbarClosed );
// add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue
self._page.addClass( self.options.classes.pagePanel );
// if animating, add the class to do so
if ( $.support.cssTransform3d && !!self.options.animate ) {
this.element.addClass( self.options.classes.animate );
}
self._bindUpdateLayout();
self._bindCloseEvents();
self._bindLinkListeners();
self._bindPageEvents();
if ( !!self.options.dismissible ) {
self._createModal();
}
self._bindSwipeEvents();
},
_createModal: function( options ) {
var self = this;
self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" )
.on( "mousedown", function() {
self.close();
})
.appendTo( this._page );
},
_getPosDisplayClasses: function( prefix ) {
return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display;
},
_getPanelClasses: function() {
var panelClasses = this.options.classes.panel +
" " + this._getPosDisplayClasses( this.options.classes.panel ) +
" " + this.options.classes.panelClosed;
if ( this.options.theme ) {
panelClasses += " ui-body-" + this.options.theme;
}
if ( !!this.options.positionFixed ) {
panelClasses += " " + this.options.classes.panelFixed;
}
return panelClasses;
},
_addPanelClasses: function() {
this.element.addClass( this._getPanelClasses() );
},
_bindCloseEvents: function() {
var self = this;
self._closeLink.on( "click.panel" , function( e ) {
e.preventDefault();
self.close();
return false;
});
self.element.on( "click.panel" , "a:jqmData(ajax='false')", function( e ) {
self.close();
});
},
_positionPanel: function() {
var self = this,
panelInnerHeight = self._panelInner.outerHeight(),
expand = panelInnerHeight > $.mobile.getScreenHeight();
if ( expand || !self.options.positionFixed ) {
if ( expand ) {
self._unfixPanel();
$.mobile.resetActivePageHeight( panelInnerHeight );
}
self._scrollIntoView( panelInnerHeight );
} else {
self._fixPanel();
}
},
_scrollIntoView: function( panelInnerHeight ) {
if ( panelInnerHeight < $( window ).scrollTop() ) {
window.scrollTo( 0, 0 );
}
},
_bindFixListener: function() {
this._on( $( window ), { "throttledresize": "_positionPanel" });
},
_unbindFixListener: function() {
this._off( $( window ), "throttledresize" );
},
_unfixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.removeClass( this.options.classes.panelFixed );
}
},
_fixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.addClass( this.options.classes.panelFixed );
}
},
_bindUpdateLayout: function() {
var self = this;
self.element.on( "updatelayout", function( e ) {
if ( self._open ) {
self._positionPanel();
}
});
},
_bindLinkListeners: function() {
var self = this;
self._page.on( "click.panel" , "a", function( e ) {
if ( this.href.split( "#" )[ 1 ] === self._panelID && self._panelID !== undefined ) {
e.preventDefault();
var $link = $( this ),
$parent;
if ( ! $link.hasClass( "ui-link" ) ) {
// Check if we are in a listview
$parent = $link.parent().parent();
if ( $parent.hasClass( "ui-li" ) ) {
$link = $parent.parent();
}
$link.addClass( $.mobile.activeBtnClass );
self.element.one( "panelopen panelclose", function() {
$link.removeClass( $.mobile.activeBtnClass );
});
}
self.toggle();
return false;
}
});
},
_bindSwipeEvents: function() {
var self = this,
area = self._modal ? self.element.add( self._modal ) : self.element;
// on swipe, close the panel
if( !!self.options.swipeClose ) {
if ( self.options.position === "left" ) {
area.on( "swipeleft.panel", function( e ) {
self.close();
});
} else {
area.on( "swiperight.panel", function( e ) {
self.close();
});
}
}
},
_bindPageEvents: function() {
var self = this;
self._page
// Close the panel if another panel on the page opens
.on( "panelbeforeopen", function( e ) {
if ( self._open && e.target !== self.element[ 0 ] ) {
self.close();
}
})
// clean up open panels after page hide
.on( "pagehide", function( e ) {
if ( self._open ) {
self.close( true );
}
})
// on escape, close? might need to have a target check too...
.on( "keyup.panel", function( e ) {
if ( e.keyCode === 27 && self._open ) {
self.close();
}
});
},
// state storage of open or closed
_open: false,
_contentWrapOpenClasses: null,
_fixedToolbarOpenClasses: null,
_modalOpenClasses: null,
open: function( immediate ) {
if ( !this._open ) {
var self = this,
o = self.options,
_openPanel = function() {
self._page.off( "panelclose" );
self._page.jqmData( "panel", "open" );
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page
.removeClass( self._pageTheme )
.addClass( "ui-body-" + self.options.theme );
}
self.element.removeClass( o.classes.panelClosed ).addClass( o.classes.panelOpen );
self._positionPanel();
// Fix for IE7 min-height bug
if ( self.options.theme && self.options.display !== "overlay" ) {
self._wrapper.css( "min-height", self._page.css( "min-height" ) );
}
self._contentWrapOpenClasses = self._getPosDisplayClasses( o.classes.contentWrap );
self._wrapper
.removeClass( o.classes.contentWrapClosed )
.addClass( self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen );
self._fixedToolbarOpenClasses = self._getPosDisplayClasses( o.classes.contentFixedToolbar );
self._fixedToolbar
.removeClass( o.classes.contentFixedToolbarClosed )
.addClass( self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen );
self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen;
if ( self._modal ) {
self._modal.addClass( self._modalOpenClasses );
}
},
complete = function() {
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self._page.addClass( o.classes.pagePanelOpen );
self._bindFixListener();
self._trigger( "open" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeopen" );
if ( self._page.jqmData('panel') === "open" ) {
self._page.on( "panelclose", function() {
_openPanel();
});
} else {
_openPanel();
}
self._open = true;
}
},
close: function( immediate ) {
if ( this._open ) {
var o = this.options,
self = this,
_closePanel = function() {
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
self._page.removeClass( o.classes.pagePanelOpen );
self.element.removeClass( o.classes.panelOpen );
self._wrapper.removeClass( o.classes.contentWrapOpen );
self._fixedToolbar.removeClass( o.classes.contentFixedToolbarOpen );
if ( self._modal ) {
self._modal.removeClass( self._modalOpenClasses );
}
},
complete = function() {
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page.removeClass( "ui-body-" + self.options.theme ).addClass( self._pageTheme );
// reset fix for IE7 min-height bug
self._wrapper.css( "min-height", "" );
}
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self.element.addClass( o.classes.panelClosed );
self._wrapper
.removeClass( self._contentWrapOpenClasses )
.addClass( o.classes.contentWrapClosed );
self._fixedToolbar
.removeClass( self._fixedToolbarOpenClasses )
.addClass( o.classes.contentFixedToolbarClosed );
self._fixPanel();
self._unbindFixListener();
$.mobile.resetActivePageHeight();
self._page.jqmRemoveData( "panel" );
self._trigger( "close" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeclose" );
_closePanel();
self._open = false;
}
},
toggle: function( options ) {
this[ this._open ? "close" : "open" ]();
},
_transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd",
_destroy: function() {
var classes = this.options.classes,
theme = this.options.theme,
hasOtherSiblingPanels = this.element.siblings( "." + classes.panel ).length;
// create
if ( !hasOtherSiblingPanels ) {
this._wrapper.children().unwrap();
this._page.find( "a" ).unbind( "panelopen panelclose" );
this._page.removeClass( classes.pagePanel );
if ( this._open ) {
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
$.mobile.resetActivePageHeight();
}
} else if ( this._open ) {
this._wrapper.removeClass( classes.contentWrapOpen );
this._fixedToolbar.removeClass( classes.contentFixedToolbarOpen );
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
}
this._panelInner.children().unwrap();
this.element.removeClass( [ this._getPanelClasses(), classes.panelAnimate ].join( " " ) )
.off( "swipeleft.panel swiperight.panel" )
.off( "panelbeforeopen" )
.off( "panelhide" )
.off( "keyup.panel" )
.off( "updatelayout" );
this._closeLink.off( "click.panel" );
if ( this._modal ) {
this._modal.remove();
}
// open and close
this.element.off( this._transitionEndEvents )
.removeClass( [ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.panel.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.table", $.mobile.widget, {
options: {
classes: {
table: "ui-table"
},
initSelector: ":jqmData(role='table')"
},
_create: function() {
var self = this;
self.refresh( true );
},
refresh: function (create) {
var self = this,
trs = this.element.find( "thead tr" );
if ( create ) {
this.element.addClass( this.options.classes.table );
}
// Expose headers and allHeaders properties on the widget
// headers references the THs within the first TR in the table
self.headers = this.element.find( "tr:eq(0)" ).children();
// allHeaders references headers, plus all THs in the thead, which may include several rows, or not
self.allHeaders = self.headers.add( trs.children() );
trs.each(function(){
var coltally = 0;
$( this ).children().each(function( i ){
var span = parseInt( $( this ).attr( "colspan" ), 10 ),
sel = ":nth-child(" + ( coltally + 1 ) + ")";
$( this )
.jqmData( "colstart", coltally + 1 );
if( span ){
for( var j = 0; j < span - 1; j++ ){
coltally++;
sel += ", :nth-child(" + ( coltally + 1 ) + ")";
}
}
if ( create === undefined ) {
$(this).jqmData("cells", "");
}
// Store "cells" data on header as a reference to all cells in the same column as this TH
$( this )
.jqmData( "cells", self.element.find( "tr" ).not( trs.eq(0) ).not( this ).children( sel ) );
coltally++;
});
});
// update table modes
if ( create === undefined ) {
this.element.trigger( 'refresh' );
}
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.table.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "columntoggle";
$.mobile.table.prototype.options.columnBtnTheme = null;
$.mobile.table.prototype.options.columnPopupTheme = null;
$.mobile.table.prototype.options.columnBtnText = "Columns...";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
popup: "ui-table-columntoggle-popup",
columnBtn: "ui-table-columntoggle-btn",
priorityPrefix: "ui-table-priority-",
columnToggleTable: "ui-table-columntoggle"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
self = $table.data( "mobile-table" ),
event = e.type,
o = self.options,
ns = $.mobile.ns,
id = ( $table.attr( "id" ) || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */
$menuButton,
$popup,
$menu,
$switchboard;
if ( o.mode !== "columntoggle" ) {
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.columnToggleTable );
$menuButton = $( "<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>" ),
$popup = $( "<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"),
$menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>");
}
// create the hide/show toggles
self.headers.not( "td" ).each(function( i ) {
var priority = $( this ).jqmData( "priority" ),
$cells = $( this ).add( $( this ).jqmData( "cells" ) );
if ( priority ) {
$cells.addClass( o.classes.priorityPrefix + priority );
if ( event !== "refresh" ) {
$("<label><input type='checkbox' checked />" + $( this ).text() + "</label>" )
.appendTo( $menu )
.children( 0 )
.jqmData( "cells", $cells )
.checkboxradio({
theme: o.columnPopupTheme
});
} else {
$( '#' + id + ' fieldset div:eq(' + i +')').find('input').jqmData( 'cells', $cells );
}
}
});
if ( event !== "refresh" ) {
$menu.appendTo( $popup );
}
// bind change event listeners to inputs - TODO: move to a private method?
if ( $menu === undefined ) {
$switchboard = $('#' + id + ' fieldset');
} else {
$switchboard = $menu;
}
if ( event !== "refresh" ) {
$switchboard.on( "change", "input", function( e ){
if( this.checked ){
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
} else {
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
}
});
$menuButton
.insertBefore( $table )
.buttonMarkup({
theme: o.columnBtnTheme
});
$popup
.insertBefore( $table )
.popup();
}
// refresh method
self.update = function(){
$switchboard.find( "input" ).each( function(){
if (this.checked) {
this.checked = $( this ).jqmData( "cells" ).eq(0).css( "display" ) === "table-cell";
if (event === "refresh") {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-visible');
}
} else {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-hidden');
}
$( this ).checkboxradio( "refresh" );
});
};
$.mobile.window.on( "throttledresize", self.update );
self.update();
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "reflow";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
reflowTable: "ui-table-reflow",
cellLabels: "ui-table-cell-label"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
event = e.type,
self = $table.data( "mobile-table" ),
o = self.options;
// If it's not reflow mode, return here.
if( o.mode !== "reflow" ){
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.reflowTable );
}
// get headers in reverse order so that top-level headers are appended last
var reverseHeaders = $( self.allHeaders.get().reverse() );
// create the hide/show toggles
reverseHeaders.each(function( i ){
var $cells = $( this ).jqmData( "cells" ),
colstart = $( this ).jqmData( "colstart" ),
hierarchyClass = $cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top",
text = $(this).text();
if( text !== "" ){
if( hierarchyClass ){
var iteration = parseInt( $( this ).attr( "colspan" ), 10 ),
filter = "";
if( iteration ){
filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")";
}
$cells.filter( filter ).prepend( "<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>" );
}
else {
$cells.prepend( "<b class='" + o.classes.cellLabels + "'>" + text + "</b>" );
}
}
});
});
})( jQuery );
(function( $, window ) {
$.mobile.iosorientationfixEnabled = true;
// This fix addresses an iOS bug, so return early if the UA claims it's something else.
var ua = navigator.userAgent;
if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ){
$.mobile.iosorientationfixEnabled = false;
return;
}
var zoom = $.mobile.zoom,
evt, x, y, z, aig;
function checkTilt( e ) {
evt = e.originalEvent;
aig = evt.accelerationIncludingGravity;
x = Math.abs( aig.x );
y = Math.abs( aig.y );
z = Math.abs( aig.z );
// If portrait orientation and in one of the danger zones
if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) {
if ( zoom.enabled ) {
zoom.disable();
}
} else if ( !zoom.enabled ) {
zoom.enable();
}
}
$.mobile.document.on( "mobileinit", function(){
if( $.mobile.iosorientationfixEnabled ){
$.mobile.window
.bind( "orientationchange.iosorientationfix", zoom.enable )
.bind( "devicemotion.iosorientationfix", checkTilt );
}
});
}( jQuery, this ));
(function( $, window, undefined ) {
var $html = $( "html" ),
$head = $( "head" ),
$window = $.mobile.window;
//remove initial build class (only present on first pageshow)
function hideRenderingClass() {
$html.removeClass( "ui-mobile-rendering" );
}
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$( window.document ).trigger( "mobileinit" );
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if ( !$.mobile.gradeA() ) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ( $.mobile.ajaxBlacklist ) {
$.mobile.ajaxEnabled = false;
}
// Add mobile, initial load "rendering" classes to docEl
$html.addClass( "ui-mobile ui-mobile-rendering" );
// This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
// this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
setTimeout( hideRenderingClass, 5000 );
$.extend( $.mobile, {
// find and enhance the pages in the dom and transition to the first page.
initializePage: function() {
// find present pages
var path = $.mobile.path,
$pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ),
hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ),
hashPage = document.getElementById( hash );
// if no pages are found, create one with body's inner html
if ( !$pages.length ) {
$pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
}
// add dialogs, set data-url attrs
$pages.each(function() {
var $this = $( this );
// unless the data url is already set set it to the pathname
if ( !$this.jqmData( "url" ) ) {
$this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $.mobile.firstPage.parent().addClass( "ui-mobile-viewport" );
// initialize navigation events now, after mobileinit has occurred and the page container
// has been created but before the rest of the library is alerted to that fact
$.mobile.navreadyDeferred.resolve();
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger( "pagecontainercreate" );
// cue page loading message
$.mobile.showPageLoadingMsg();
//remove initial build class (only present on first pageshow)
hideRenderingClass();
// if hashchange listening is disabled, there's no hash deeplink,
// the hash is not valid (contains more than one # or does not start with #)
// or there is no page with that hash, change to the first page in the DOM
// Remember, however, that the hash can also be a path!
if ( ! ( $.mobile.hashListeningEnabled &&
$.mobile.path.isHashValid( location.hash ) &&
( $( hashPage ).is( ':jqmData(role="page")' ) ||
$.mobile.path.isPath( hash ) ||
hash === $.mobile.dialogHashKey ) ) ) {
// Store the initial destination
if ( $.mobile.path.isHashValid( location.hash ) ) {
$.mobile.urlHistory.initialDst = hash.replace( "#", "" );
}
// make sure to set initial popstate state if it exists
// so that navigation back to the initial page works properly
if( $.event.special.navigate.isPushStateEnabled() ) {
$.mobile.navigate.navigator.squash( path.parseLocation().href );
}
$.mobile.changePage( $.mobile.firstPage, {
transition: "none",
reverse: true,
changeHash: false,
fromHashChange: true
});
} else {
// trigger hashchange or navigate to squash and record the correct
// history entry for an initial hash path
if( !$.event.special.navigate.isPushStateEnabled() ) {
$window.trigger( "hashchange", [true] );
} else {
// TODO figure out how to simplify this interaction with the initial history entry
// at the bottom js/navigate/navigate.js
$.mobile.navigate.history.stack = [];
$.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href );
}
}
}
});
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function() {
window.scrollTo( 0, 1 );
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1;
//dom-ready inits
if ( $.mobile.autoInitializePage ) {
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
if ( !$.support.cssPointerEvents ) {
// IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
// by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
// https://github.com/jquery/jquery-mobile/issues/3558
$.mobile.document.delegate( ".ui-disabled", "vclick",
function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
}
);
}
});
}( jQuery, this ));
}));
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | davertron/react-router | import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
pootle/static/js/auth/components/SignInForm.js | mail-apps/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
'use strict';
import assign from 'object-assign';
import React from 'react';
import { FormElement } from 'components/forms';
import { FormMixin } from 'mixins/forms';
let SignInForm = React.createClass({
mixins: [FormMixin],
propTypes: {
canRegister: React.PropTypes.bool.isRequired,
formErrors: React.PropTypes.object.isRequired,
isLoading: React.PropTypes.bool.isRequired,
},
/* Lifecycle */
getInitialState() {
// XXX: initialData required by `FormMixin`; this is really OBSCURE
this.initialData = {
login: '',
password: '',
};
return {
formData: assign({}, this.initialData),
};
},
componentWillReceiveProps(nextProps) {
if (this.state.errors !== nextProps.formErrors) {
this.setState({errors: nextProps.formErrors});
}
},
/* Handlers */
handleRequestPasswordReset(e) {
e.preventDefault();
this.props.flux.getActions('auth').gotoScreen('requestPasswordReset');
},
handleSignUp(e) {
e.preventDefault();
this.props.flux.getActions('auth').gotoScreen('signUp');
},
handleFormSubmit(e) {
e.preventDefault();
let nextURL = window.location.pathname + window.location.hash;
this.props.flux.getActions('auth').signIn(this.state.formData, nextURL);
},
/* Others */
hasData() {
let { formData } = this.state;
return formData.login !== '' && formData.password !== '';
},
/* Layout */
render() {
let { errors } = this.state;
let { formData } = this.state;
let signUp = this.props.canRegister ?
<a href="#" onClick={this.handleSignUp}>
{gettext('Sign up as a new user')}
</a> :
<p>{gettext('Creating new user accounts is prohibited.')}</p>;
return (
<form
method="post"
onSubmit={this.handleFormSubmit}
>
<div className="fields">
<FormElement
attribute="login"
label={gettext('Username')}
autoFocus={true}
handleChange={this.handleChange}
formData={formData}
errors={errors}
/>
<FormElement
type="password"
attribute="password"
label={gettext('Password')}
handleChange={this.handleChange}
formData={formData}
errors={errors}
/>
<div className="actions password-forgotten">
<a href="#" onClick={this.handleRequestPasswordReset}>
{gettext('I forgot my password')}
</a>
</div>
{this.renderAllFormErrors()}
</div>
<div className="actions">
<div>
<input
type="submit"
className="btn btn-primary"
disabled={!this.hasData() || this.props.isLoading}
value={gettext('Sign In')}
/>
</div>
<div>
{signUp}
</div>
</div>
</form>
);
}
});
export default SignInForm;
|
src/View/windows/index.js | gabrielbull/react-desktop | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Width, { widthPropTypes } from '../../style/width';
import Margin, { marginPropTypes } from '../../style/margin';
import Padding, { paddingPropTypes } from '../../style/padding';
import Alignment, { alignmentPropTypes } from '../../style/alignment';
import Background, { backgroundContextTypes } from '../../style/background/windows';
import Hidden, { hiddenPropTypes } from '../../style/hidden';
import Dimension, { dimensionPropTypes } from '../../style/dimension';
import { ColorContext } from '../../style/color/windows';
import { ThemeContext } from '../../style/theme/windows';
var styles = {
display: 'flex',
position: 'relative'
};
@Width()
@Dimension()
@Alignment()
@Margin()
@Padding()
@Background()
@Hidden()
@ColorContext()
@ThemeContext()
class View extends Component {
static propTypes = {
...alignmentPropTypes,
...widthPropTypes,
...marginPropTypes,
...paddingPropTypes,
...backgroundContextTypes,
...hiddenPropTypes,
...dimensionPropTypes,
direction: PropTypes.string,
layout: PropTypes.string
};
static defaultProps = {
layout: 'horizontal'
};
render() {
let { horizontalAlignment, children, style, direction, layout, ...props } = this.props;
let componentStyle = { ...styles, ...style };
if (direction) {
// direction will be deprecated on v0.3 and a warning will be shown
layout = direction === 'column' ? 'vertical' : 'horizontal';
}
if (layout === 'vertical') {
componentStyle.flexDirection = 'column';
if (horizontalAlignment) {
switch(horizontalAlignment) {
case 'center': componentStyle.alignItems = 'center'; break;
case 'left': componentStyle.alignItems = 'flex-start'; break;
case 'right': componentStyle.alignItems = 'flex-end'; break;
}
}
} else {
if (horizontalAlignment) {
switch(horizontalAlignment) {
case 'center': componentStyle.justifyContent = 'center'; break;
case 'left': componentStyle.justifyContent = 'flex-start'; break;
case 'right': componentStyle.justifyContent = 'flex-end'; break;
}
}
}
return (
<div
style={componentStyle}
{...props}
>
{children}
</div>
);
}
}
export default View;
|
Ejemplos/react-redux-plantilla-reducida/src/index.js | TheSuperJez/ReactWebAppsCourse | import '../less/main.less';
import _ from 'underscore';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './store';
import {Provider} from 'react-redux';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
window._ = _;
const store = configureStore();
render(
<Provider store={store}>
<Router history={hashHistory} routes={routes} />
</Provider>,
document.getElementById('app')
);
|
app/views/my-achievements/achievements-texts.js | GuenoleK/portfolio | import React from 'react';
class AchievementsTextsRender {
renderItSchoolArticleContent() {
return(
<div className="it-school">
Au sein des écoles, les institutrices sont souvent confrontées à des problèmes logistiques tels que l’utilisation conséquente de papier et d’encre pour imprimer leurs exercices.<br/>
Afin de se passer du support papier, notre but est de matérialiser les exercices créés par les enseignants au format numérique comme le coloriage, les jeux de course, memory, etc.<br/><br/>
La préparation des supports d’exercices sera simplifiée et permettra un gain de temps.<br/>
Ainsi, les maîtresses pourront utiliser des exercices crées au préalables ou générer leurs propres exercices. <br/>
Elles pourront évaluer le niveau des élèves afin de les orienter dans les révisions. <br/>
Cela permettra aussi de travailler en groupe, d’enseigner l’autonomie aux enfants, mais aussi qu’ils puissent apprendre à leur rythme tout en s’amusant à travers différentes activités ludiques.<br/><br/>
Ce projet a été développé durant un an lors de ma 3e année de scolarité à IN’TECH.<br/>
Afin de réaliser ce projet, nous étions une équipe de 3 développeurs.<br/>
Ce projet a été présenté à une équipe de professeurs dans une école privée et à des enfants d’une classe.<br/>
Le résultat est que notre application a énormément plu et que l’école souhaite faire une collaboration avec nous afin de mettre en place un module durant lequel les enfants pourraient profiter de cette application ludo-éducative. <br/>
De plus, les professeurs souhaitent que nous puissions continuer à mettre à jour le contenu avec ce qu’ils peuvent nous transmettre en termes de fonctionnalités voulu et améliorations.<br/><br/>
Ce projet a été une expérience unique qui m’a donné l’envie de me lancer dans la création d’une structure qui nous permettra, à moi et à mes camarades, de continuer de développer des projets ambitieux et utiles tels que celui-ci.<br/>
Notre manque d’expérience professionnel nous a parfois porté préjudice lors du développement faisant que nous étions souvent dépassés par les événements et la charge de travail.<br/>
Aujourd’hui, nous sommes tous apte et mieux gérer un projet de cette ampleur grâce aux différentes techniques de gestion et à nos compétences techniques que nous avons amélioré durant notre période d’alternance.
</div>
);
}
renderProxItiArticleContent() {
return(
<div className="prox-iti">
L'association Proxité agit au coeur des quartiers populaires en faveur de l'insertion scolaire et professionnelle des jeunes, en leur proposant un accompagnement individuel par des bénévoles actifs dans le monde du travail.<br/>
Notre objectif était, durant un semestre, d'attirer 5 à 10 jeunes dans l'association Proxité à Ivry-Sur-Sein par des actions de communications.<br/><br/>
Nous étions une équipe de 4 personnes et nous avons usés de plusieurs moyens de communications pouvant permettre d’atteindre nos objectifs.<br/>
Nous avons eu l’autorisation de plusieurs établissements afin de mettre en avant des affiches que nous avons nous-même crées, nous avons fait une communication en interne dans l’école afin que le bouche à oreille puisse aussi se faire dans les locaux de l’établissement et nous avons eu un stand lors de l’un des événements les plus important qu’est « Ivry en Fête ».<br/>
Durant cet événement, les associations de la ville ont des stands dédiés afin de présenter leur activité aux passants. C’est là que nous avons eu le plus de retour et d’inscriptions pour l’association. C’était un franc succès.<br/><br/>
L’intérêt de ce projet était non seulement d’aider l’association pour son ouverture dans la ville, mais aussi d’acquérir des compétences non techniques qui me servent encore aujourd’hui telles que la communication, l’esprit d’équipe ou encore la persévérance.
</div>
);
}
renderFocusArticleContent() {
return(
<div className="focus">
Lors de mon stage de 3e année d’étude (Février-Août 2016) j’ai intégré l’équipe Focus qui a été un pôle « Innovation » au sein de KLEE Group.<br/>
Au sein de cette équipe, j’ai aidé au développement et à la maintenance des librairies techniques qui étaient mises en place pour aider à la productivité des développeurs et à un ensemble de bonnes pratiques qui aident à faire du développement moderne.<br/>
La méthode de travail est la méthode agile SCRUM au sein de cette équipe qui permet de travailler sous forme itérative. Cette période itérative est une période appelée sprint, c’est une période intensive de travail et de production.<br/><br/>
<h4>Focus-Components</h4>
Focus-Components est une librairie open-source de composants web. Ils sont essentiellement réalisés avec le framework ReactJS et donc codés essentiellement en JavaScript. Le but de cette librairie est de créer des composants web prêts à l’utilisation sur des projets.<br/>
L’ensemble des technologies que j’ai utilisé sont donc : <br/>
<ul>
<li><b>Git :</b> grâce à git, nous pouvions avoir un historique du travail fourni, donc avoir les différentes versions de ce qui était fait et livré. Pour faciliter cela, nous avons utilisé le site GitHub qui est un hébergeur du développement fourni.</li>
<li>
<b>JavaScript :</b> c’est le langage qui était globalement utilisé au sein du développement de la librairie et de la gestion du composant.
<ul>
<li>Pour la partie « rendu » du composant, c’est le framework ReactJS, développé par Facebook, qui a été utilisé. De plus le framework SASS (extension de CSS3), permet de variabiliser le CSS.</li>
<li>Concernant le packaging de la librairie pour son utilisation au sein des projets, c’est la librairie Webpack qui nous permettant de rassembler l’ensemble du code fourni en un seul et même fichier de package.</li>
</ul>
</li>
</ul><br/>
<h4>Centre d’aide Focus</h4>
Pour ce projet, j’étais en binôme avec un des membres du projet pour lequel cette application avait été vendue. Nous avons travaillé de manière agile, en gardant la méthode SCRUM.<br/>
Pour les technologies utilisées, nous sommes globalement restés sur celles utilisées par mon équipe.<br/>
<ul>
<li>Pour les technologies côté vue, nous avons utilisé le JavaScript, ReactJS et Redux pour la partie de synchronisation de l’application. Le TypeScript a été utilisé afin de typer le JavaScript et d’avoir un contrôle plus poussé, donnant accès aussi à de la documentation simplifiée sur le code. Un framework de test appelé Enzyme a été mis en place pour les tests unitaires côté Front-End.</li>
<li>NodeJS pour la partie serveur permettant le lancement de l’application</li>
<li>Sequelize qui est un ORM JavaScript. ORM signifie Object-Relationnal-Mapping. C’est une technique de programmation qui permet de créer une base de données orientée objet à partir d’une base de données relationnelle.
J’ai beaucoup appris tout le long de l’élaboration de ce projet. Il y a des choses que je ne savais pas faire, mais cela était normal car le cursus scolaire ne permet pas de tout voir. Il y a des choses que l’on apprend une fois en entreprise et mes collègues me l’ont rappelé. Ils m’ont aidé à gérer la pression en me rappelant qu’ils étaient là pour que j’apprenne. Cela a été efficace car j’ai pu beaucoup observer, consolider mes connaissances en reactJS et javascript et ai pu faire de la programmation orientée objet avec le TypeScript qui était utilisé pour définir les modèles de base de données entre autres.</li>
</ul><br/>
J’ai donc développé en binôme pendant 25 jours et durant le mois restant j’ai dû être autonome, tout en gardant les conseils de mes responsables.<br/>
Nous avons pu arriver au bout de ce qui avait été défini. N’ayant pas l’application du client, nous avons intégré l’extension dans Focus Demo afin de voir comment cela rendait.<br/>
</div>
);
}
renderPortfolioArticleContent() {
return(
<div className="portfolio">
C’est, notamment, le site sur lequel vous vous trouvez actuellement. <br/>
C’est à la base un des documents à fournir à la fin de la 2e année de master. Il sert, entre autres, en partie à valider le master.<br/>
Nous avions le choix de le faire soit avec un programme informatique (CMS : Content Managment System) qui permet de créer rapidement un site internet ou alors de le faire nous-même.<br/><br/>
J’ai décidé de me lancer ce challenge afin de tester mes compétences de développeur et ma créativité. Souhaitant me spécialiser dans le développement Front-End, je me devais de relever ce défi.<br/>
L’enjeu était donc de développer moi-même cet outil mais aussi de pouvoir le montrer aux yeux de tous afin d’être contacté directement via cette plateforme par des professionnels.<br/><br/>
J’ai été totalement seul à développer mon portfolio. Je me suis cependant aidé du langage de programmation et de librairies que je préfère. Soit le JavaScript accompagné des différentes librairies JavaScript qui m’ont permis de créer différents composants web et effets qui se trouvent sur le site.<br/><br/>
Je suis fier de voir ce site en ligne, que je maintiendrai à jour et que je peux présenter auprès de ceux qui veulent voir ce que je sais faire. De plus, le site est open-source et disponible sur GitHub.<br/>
Je mets donc à disposition mon portfolio afin de recevoir des avis qui pourraient m’aider à améliorer ce que j’ai fait.<br/><br/>
J’ai étalé le développement de mon portfolio sur mes 2 ans de master. Je pense que je pourrai, à l’avenir, prendre le temps exact que je passe à développer un outil afin de pouvoir améliorer mes performances et savoir en combien de temps je peux exécuter certaines tâches.<br/>
</div>
);
}
}
export const achievementsTextsRender = new AchievementsTextsRender();
|
spec/components/chip.js | VACO-GitHub/vaco-components-library | import React from 'react';
import Avatar from '../../components/avatar';
import Chip from '../../components/chip';
import style from '../style';
class ChipTest extends React.Component {
state = {
deleted: false
};
handleDeleteClick = () => {
this.setState({
deleted: true
});
};
render () {
return (
<section>
<h5>Chips</h5>
<p>Chips can be deletable and have an avatar.</p>
<Chip>Example chip</Chip>
<Chip>
<span style={{textDecoration: 'line-through'}}>Standard</span>
<strong>Custom</strong> chip <small>(custom markup)</small>
</Chip>
{
this.state.deleted ? null : (
<Chip
deletable
onDeleteClick={this.handleDeleteClick}
>
Deletable Chip
</Chip>
)
}
<Chip>
<Avatar style={{backgroundColor: 'deepskyblue'}} icon="folder" />
<span>Avatar Chip</span>
</Chip>
<Chip>
<Avatar title="A" /><span>Initial chip</span>
</Chip>
<Chip>
<Avatar><img src="https://placeimg.com/80/80/animals"/></Avatar>
<span>Image contact chip</span>
</Chip>
<div className={style.chipTruncateWrapper}>
<Chip deletable>
Truncated chip with long label. Lorem ipsum Amet quis mollit Excepteur id dolore.
</Chip>
</div>
</section>
);
}
}
export default ChipTest;
|
src/app/core/atoms/icon/icons/drydock.js | blowsys/reservo | import React from 'react'; const Drydock = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><polygon points="17 10 17 6 14 6 13 3 11 3 10 6 7 6 7 10"/><path d="M22,20 L2,20 L2,16 L4,16 L4,18 L6.65365619,18 C6.59928001,17.9057703 6.55210536,17.8062365 6.513,17.702 L4,11 L10,11 L12,14 L14,11 L13,11 L20,11 L17.487,17.702 C17.4478946,17.8062365 17.40072,17.9057703 17.3463438,18 L20,18 L20,16 L22,16 L22,20 Z"/></g></g></svg>; export default Drydock;
|
app/Components/AuthSlack.js | DaftMonk/sweet-sound-client | import React from 'react';
import qs from 'qs';
const clientId = process.env.NODE_ENV === 'production' ?
'2376554812.23846206866':
'2376554812.23645499953';
const clientSecret = process.env.NODE_ENV === 'production' ?
'0aafceac20b11bf475e1ca5118390811' :
'a8fc14196984beee9faa03c827d90dc0';
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
export default class AuthSlack extends React.Component {
componentDidMount() {
let slackCode = getQueryString('code');
if(slackCode) {
this.getAccessToken(slackCode);
}
}
getAccessToken(code) {
fetch('https://slack.com/api/oauth.access?' + qs.stringify({
client_id: clientId,
client_secret: clientSecret,
code
}), {
method: 'get',
})
.then((r) => r.json())
.then((resp) => {
this.props.onAuthenticated(resp);
});
}
render() {
let authUrl = "https://slack.com/oauth/authorize?client_id=" + clientId + "&scope=chat%3Awrite%3Auser"
return (
<a href={authUrl} className="btn btn-default" onClick={this.signIn}>
<em>#</em> Sign in with Slack
</a>
);
}
} |
src/client/components/svg/svg.container.js | DBCDK/tanterne | /* eslint-disable */
import React from 'react';
export const Arrow = ({className = ''}) => {
return (
<svg className={`arrow ${className}`} height="32px" viewBox="0 0 32 32" width="32px">
<path
d="M24.285,11.284L16,19.571l-8.285-8.288c-0.395-0.395-1.034-0.395-1.429,0 c-0.394,0.395-0.394,1.035,0,1.43l8.999,9.002l0,0l0,0c0.394,0.395,1.034,0.395,1.428,0l8.999-9.002 c0.394-0.395,0.394-1.036,0-1.431C25.319,10.889,24.679,10.889,24.285,11.284z"
/>
</svg>
);
};
export const Plus = ({className = ''}) => {
return (
<svg className={`plus ${className}`} viewBox="0 0 56 56" >
<path d="M28,.5a28,28,0,1,0,28,28A28,28,0,0,0,28,.5ZM28,53A24.5,24.5,0,1,1,52.5,28.5,24.53,24.53,0,0,1,28,53Z"/>
<path d="M42,26.75H29.75V14.5a1.75,1.75,0,0,0-3.5,0V26.75H14a1.75,1.75,0,0,0,0,3.5H26.25V42.5a1.75,1.75,0,0,0,3.5,0V30.25H42a1.75,1.75,0,0,0,0-3.5Z"/>
</svg>
);
};
|
Ranta.ReactjsDemo/Scripts/react/react-dom-server.js | ranta-demo/Ranta.ReactJsDemo | /**
* ReactDOMServer v0.14.7
*
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js
;(function(f) {
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f(require('react'));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(['react'], f);
// <script>
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// see https://github.com/facebook/react/issues/3037
g = this;
}
g.ReactDOMServer = f(g.React);
}
})(function(React) {
return React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
});
|
ajax/libs/vue/2.0.5/vue.runtime.js | kennynaoh/cdnjs | /*!
* Vue.js v2.0.5
* (c) 2014-2016 Evan You
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Vue = factory());
}(this, (function () { 'use strict';
/* */
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val, 10);
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove$1 (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
/**
* Camelize a hyphen-delmited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind$1 (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
var toString = Object.prototype.toString;
var OBJECT_STRING = '[object Object]';
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
/* eslint-disable eqeqeq */
return a == b || (
isObject(a) && isObject(b)
? JSON.stringify(a) === JSON.stringify(b)
: false
)
/* eslint-enable eqeqeq */
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: null,
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100,
/**
* Server rendering?
*/
_isServer: process.env.VUE_ENV === 'server'
};
/* */
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
} else {
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser =
typeof window !== 'undefined' &&
Object.prototype.toString.call(window) !== '[object Object]';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return /native code/.test(Ctor.toString())
}
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
timerFunc = function () {
p.then(nextTickHandler);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var func = ctx
? function () { cb.call(ctx); }
: cb;
callbacks.push(func);
if (!pending) {
pending = true;
timerFunc();
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] !== undefined
};
Set.prototype.add = function add (key) {
this.set[key] = 1;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* not type checking this file because flow doesn't play well with Proxy */
var hasProxy;
var proxyHandlers;
var initProxy;
if (process.env.NODE_ENV !== 'production') {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
proxyHandlers = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
}
return has || !isAllowed
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var uid$2 = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$2++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove$1(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/* */
var queue = [];
var has$1 = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0;
has$1 = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
var watcher = queue[index];
var id = watcher.id;
has$1[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has$1[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
resetSchedulerState();
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has$1[id] == null) {
has$1[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$1 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
if ( options === void 0 ) options = {};
this.vm = vm;
vm._watchers.push(this);
// options
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
this.expression = expOrFn.toString();
this.cb = cb;
this.id = ++uid$1; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value = this.getter.call(this.vm, this.vm);
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
process.env.NODE_ENV !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
);
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm);
} else {
throw e
}
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed or is performing a v-for
// re-render (the watcher list is then filtered by v-for).
if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) {
remove$1(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* istanbul ignore next
*/
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!config._isServer &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
if (newVal === value) {
return
}
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (obj, key, val) {
if (Array.isArray(obj)) {
obj.length = Math.max(obj.length, key);
obj.splice(key, 1, val);
return val
}
if (hasOwn(obj, key)) {
obj[key] = val;
return
}
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return
}
if (!ob) {
obj[key] = val;
return
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (obj, key) {
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(obj, key)) {
return
}
delete obj[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = void 0, i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
function initState (vm) {
vm._watchers = [];
initProps(vm);
initData(vm);
initComputed(vm);
initMethods(vm);
initWatch(vm);
}
function initProps (vm) {
var props = vm.$options.props;
if (props) {
var propsData = vm.$options.propsData || {};
var keys = vm.$options._propKeys = Object.keys(props);
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( i ) {
var key = keys[i];
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
} else {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm));
}
};
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true;
}
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object.',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else {
proxy(vm, keys[i]);
}
}
// observe data
observe(data);
data.__ob__ && data.__ob__.vmCount++;
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function initComputed (vm) {
var computed = vm.$options.computed;
if (computed) {
for (var key in computed) {
var userDef = computed[key];
if (typeof userDef === 'function') {
computedSharedDefinition.get = makeComputedGetter(userDef, vm);
computedSharedDefinition.set = noop;
} else {
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind$1(userDef.get, vm)
: noop;
computedSharedDefinition.set = userDef.set
? bind$1(userDef.set, vm)
: noop;
}
Object.defineProperty(vm, key, computedSharedDefinition);
}
}
}
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
});
return function computedGetter () {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
function initMethods (vm) {
var methods = vm.$options.methods;
if (methods) {
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm);
if (process.env.NODE_ENV !== 'production') {
methods[key] == null && warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
hasOwn(Vue$1.prototype, key) && warn(
("Avoid overriding Vue's internal method \"" + key + "\"."),
vm
);
}
}
}
}
function initWatch (vm) {
var watch = vm.$options.watch;
if (watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () {
return this._data
};
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return vm._data[key]
},
set: function proxySetter (val) {
vm._data[key] = val;
}
});
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
ns,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = ns;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.child = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var emptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.ns,
vnode.context,
vnode.componentOptions
);
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
function mergeVNodeHook (def, hookKey, hook, key) {
key = key + hookKey;
var injectedHash = def.__injected || (def.__injected = {});
if (!injectedHash[key]) {
injectedHash[key] = true;
var oldHook = def[hookKey];
if (oldHook) {
def[hookKey] = function () {
oldHook.apply(this, arguments);
hook.apply(this, arguments);
};
} else {
def[hookKey] = hook;
}
}
}
/* */
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, fn, event, capture;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (!cur) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + name + "\": got " + String(cur),
vm
);
} else if (!old) {
capture = name.charAt(0) === '!';
event = capture ? name.slice(1) : name;
if (Array.isArray(cur)) {
add(event, (cur.invoker = arrInvoker(cur)), capture);
} else {
if (!cur.invoker) {
fn = cur;
cur = on[name] = {};
cur.fn = fn;
cur.invoker = fnInvoker(cur);
}
add(event, cur.invoker, capture);
}
} else if (cur !== old) {
if (Array.isArray(old)) {
old.length = cur.length;
for (var i = 0; i < old.length; i++) { old[i] = cur[i]; }
on[name] = old;
} else {
old.fn = cur;
on[name] = old;
}
}
}
for (name in oldOn) {
if (!on[name]) {
event = name.charAt(0) === '!' ? name.slice(1) : name;
remove$$1(event, oldOn[name].invoker);
}
}
}
function arrInvoker (arr) {
return function (ev) {
var arguments$1 = arguments;
var single = arguments.length === 1;
for (var i = 0; i < arr.length; i++) {
single ? arr[i](ev) : arr[i].apply(null, arguments$1);
}
}
}
function fnInvoker (o) {
return function (ev) {
var single = arguments.length === 1;
single ? o.fn(ev) : o.fn.apply(null, arguments);
}
}
/* */
function normalizeChildren (
children,
ns,
nestedIndex
) {
if (isPrimitive(children)) {
return [createTextVNode(children)]
}
if (Array.isArray(children)) {
var res = [];
for (var i = 0, l = children.length; i < l; i++) {
var c = children[i];
var last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeChildren(c, ns, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (last && last.text) {
last.text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else if (c instanceof VNode) {
if (c.text && last && last.text) {
last.text += c.text;
} else {
// inherit parent namespace
if (ns) {
applyNS(c, ns);
}
// default key for nested array children (likely generated by v-for)
if (c.tag && c.key == null && nestedIndex != null) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
}
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
function applyNS (vnode, ns) {
if (vnode.tag && !vnode.ns) {
vnode.ns = ns;
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
applyNS(vnode.children[i], ns);
}
}
}
}
/* */
function getFirstComponentChild (children) {
return children && children.filter(function (c) { return c && c.componentOptions; })[0]
}
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this;
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = emptyVNode;
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
vm._watcher = new Watcher(vm, function () {
vm._update(vm._render(), hydrating);
}, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
};
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevActiveInstance = activeInstance;
activeInstance = vm;
var prevVnode = vm._vnode;
vm._vnode = vnode;
if (!prevVnode) {
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
vm.$el = vm.__patch__(vm.$el, vnode, hydrating);
} else {
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
if (vm._isMounted) {
callHook(vm, 'updated');
}
};
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this;
var hasChildren = !!(vm.$options._renderChildren || renderChildren);
vm.$options._parentVnode = parentVnode;
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true;
}
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
vm[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false;
}
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
vm._updateListeners(listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, vm._renderContext);
vm.$forceUpdate();
}
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove$1(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
};
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm);
}
}
vm.$emit('hook:' + hook);
}
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 };
var hooksToMerge = Object.keys(hooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
return
}
if (isObject(Ctor)) {
Ctor = Vue$1.extend(Ctor);
}
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
Ctor = Ctor.resolved;
} else {
Ctor = resolveAsyncComponent(Ctor, function () {
// it's ok to queue this on every render because
// $forceUpdate is buffered by the scheduler.
context.$forceUpdate();
});
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
}
data = data || {};
// extract props
var propsData = extractProps(data, Ctor);
// functional component
if (Ctor.options.functional) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (propOptions) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
}
var vnode = Ctor.options.render.call(
null,
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
bind$1(createElement, { _self: Object.create(context) }),
{
props: props,
data: data,
parent: context,
children: normalizeChildren(children),
slots: function () { return resolveSlots(children, context); }
}
);
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent // activeInstance in lifecycle state
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (inlineTemplate) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function init (vnode, hydrating) {
if (!vnode.child || vnode.child._isDestroyed) {
var child = vnode.child = createComponentInstanceForVnode(vnode, activeInstance);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
}
}
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions;
var child = vnode.child = oldVnode.child;
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
}
function insert (vnode) {
if (!vnode.child._isMounted) {
vnode.child._isMounted = true;
callHook(vnode.child, 'mounted');
}
if (vnode.data.keepAlive) {
vnode.child._inactive = false;
callHook(vnode.child, 'activated');
}
}
function destroy$1 (vnode) {
if (!vnode.child._isDestroyed) {
if (!vnode.data.keepAlive) {
vnode.child.$destroy();
} else {
vnode.child._inactive = true;
callHook(vnode.child, 'deactivated');
}
}
}
function resolveAsyncComponent (
factory,
cb
) {
if (factory.requested) {
// pool callbacks
factory.pendingCallbacks.push(cb);
} else {
factory.requested = true;
var cbs = factory.pendingCallbacks = [cb];
var sync = true;
var resolve = function (res) {
if (isObject(res)) {
res = Vue$1.extend(res);
}
// cache resolved
factory.resolved = res;
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res);
}
}
};
var reject = function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
};
var res = factory(resolve, reject);
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject);
}
sync = false;
// return in case resolved synchronously
return factory.resolved
}
}
function extractProps (data, Ctor) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (!propOptions) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
if (attrs || props || domProps) {
for (var key in propOptions) {
var altKey = hyphenate(key);
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = hooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (a, b) {
// since all hooks have at most two args, use fixed args
// to avoid having to use fn.apply().
return function (_, __) {
a(_, __);
b(_, __);
}
}
/* */
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
tag,
data,
children
) {
if (data && (Array.isArray(data) || typeof data !== 'object')) {
children = data;
data = undefined;
}
// make sure to use real instance instead of proxy as context
return _createElement(this._self, tag, data, children)
}
function _createElement (
context,
tag,
data,
children
) {
if (data && data.__ob__) {
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return
}
if (!tag) {
// in case of component :is set to falsy value
return emptyVNode()
}
if (typeof tag === 'string') {
var Ctor;
var ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
return createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
var childNs = tag === 'foreignObject' ? 'xhtml' : ns;
return new VNode(
tag, data, normalizeChildren(children, childNs),
undefined, undefined, ns, context
)
}
} else {
// direct component options / constructor
return createComponent(tag, data, context, children)
}
}
/* */
function initRender (vm) {
vm.$vnode = null; // the placeholder node in parent tree
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
vm._renderContext = vm.$options._parentVnode && vm.$options._parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, vm._renderContext);
// bind the public createElement fn to this instance
// so that we get proper render context inside it.
vm.$createElement = bind$1(createElement, vm);
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
nextTick(fn, this);
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
warn(("Error when rendering " + (formatComponentName(vm)) + ":"));
}
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, vm);
} else {
if (config._isServer) {
throw e
} else {
console.error(e);
}
}
// return previous vnode to prevent render error causing blank component
vnode = vm._vnode;
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = emptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// shorthands used in render functions
Vue.prototype._h = createElement;
// toString for mustaches
Vue.prototype._s = _toString;
// number conversion
Vue.prototype._n = toNumber;
// empty vnode
Vue.prototype._e = emptyVNode;
// loose equal
Vue.prototype._q = looseEqual;
// loose indexOf
Vue.prototype._i = looseIndexOf;
// render static tree by index
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
};
// mark node as static (v-once)
Vue.prototype._o = function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
};
function markStatic (tree, key, isOnce) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
// filter resolution helper
var identity = function (_) { return _; };
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
};
// render v-for
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val)) {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
return ret
};
// renderSlot
Vue.prototype._t = function (
name,
fallback
) {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
};
// apply v-bind object
Vue.prototype._b = function bindProps (
data,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key];
} else {
var hash = asProp || config.mustUseProp(key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
hash[key] = value[key];
}
}
}
}
return data
};
// expose v-on keyCodes
Vue.prototype._k = function getKeyCodes (key) {
return config.keyCodes[key]
};
}
function resolveSlots (
renderChildren,
context
) {
var slots = {};
if (!renderChildren) {
return slots
}
var children = normalizeChildren(renderChildren) || [];
var defaultSlot = [];
var name, child;
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && (name = child.data.slot)) {
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore single whitespace
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot;
}
return slots
}
/* */
function initEvents (vm) {
vm._events = Object.create(null);
// init parent attached events
var listeners = vm.$options._parentListeners;
var on = bind$1(vm.$on, vm);
var off = bind$1(vm.$off, vm);
vm._updateListeners = function (listeners, oldListeners) {
updateListeners(listeners, oldListeners || {}, on, off, vm);
};
if (listeners) {
vm._updateListeners(listeners);
}
}
function eventsMixin (Vue) {
Vue.prototype.$on = function (event, fn) {
var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn);
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
var uid = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid++;
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = vm;
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
callHook(vm, 'beforeCreate');
initState(vm);
callHook(vm, 'created');
initRender(vm);
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = Ctor.super.options;
var cachedSuperOptions = Ctor.superOptions;
var extendOptions = Ctor.extendOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed
Ctor.superOptions = superOptions;
extendOptions.render = options.render;
extendOptions.staticRenderFns = options.staticRenderFns;
options = Ctor.options = mergeOptions(superOptions, extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function Vue$1 (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue$1)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$1);
stateMixin(Vue$1);
eventsMixin(Vue$1);
lifecycleMixin(Vue$1);
renderMixin(Vue$1);
var warn = noop;
var formatComponentName;
if (process.env.NODE_ENV !== 'production') {
var hasConsole = typeof console !== 'undefined';
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
));
}
};
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
return (
(name ? ("component <" + name + ">") : "anonymous component") +
(vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '')
)
};
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages.";
}
return ("\n(found in " + str + ")")
};
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
var key, toVal, fromVal;
for (key in from) {
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isObject(toVal) && isObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and param attributes are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
var mixin = child.mixins[i];
if (mixin.prototype instanceof Vue$1) {
mixin = mixin.options;
}
parent = mergeOptions(parent, mixin, vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
var res = assets[id] ||
// camelCase ID
assets[camelize(id)] ||
// Pascal Case ID
assets[capitalize(camelize(id))];
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isBooleanType(prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
process.env.NODE_ENV !== 'production' && warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm[key] !== undefined) {
return vm[key]
}
// call factory function for non-Function types
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType);
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
/**
* Assert the type of a value
*/
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string');
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number');
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean');
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function');
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match && match[1]
}
function isBooleanType (fn) {
if (!Array.isArray(fn)) {
return getType(fn) === 'Boolean'
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === 'Boolean') {
return true
}
}
/* istanbul ignore next */
return false
}
var util = Object.freeze({
defineReactive: defineReactive$$1,
_toString: _toString,
toNumber: toNumber,
makeMap: makeMap,
isBuiltInTag: isBuiltInTag,
remove: remove$1,
hasOwn: hasOwn,
isPrimitive: isPrimitive,
cached: cached,
camelize: camelize,
capitalize: capitalize,
hyphenate: hyphenate,
bind: bind$1,
toArray: toArray,
extend: extend,
isObject: isObject,
isPlainObject: isPlainObject,
toObject: toObject,
noop: noop,
no: no,
genStaticKeys: genStaticKeys,
looseEqual: looseEqual,
looseIndexOf: looseIndexOf,
isReserved: isReserved,
def: def,
parsePath: parsePath,
hasProto: hasProto,
inBrowser: inBrowser,
UA: UA,
isIE: isIE,
isIE9: isIE9,
isEdge: isEdge,
isAndroid: isAndroid,
isIOS: isIOS,
devtools: devtools,
nextTick: nextTick,
get _Set () { return _Set; },
mergeOptions: mergeOptions,
resolveAsset: resolveAsset,
get warn () { return warn; },
get formatComponentName () { return formatComponentName; },
validateProp: validateProp
});
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else {
plugin.apply(null, args);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
Vue.options = mergeOptions(Vue.options, mixin);
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var isFirstExtend = Super.cid === 0;
if (isFirstExtend && extendOptions._Ctor) {
return extendOptions._Ctor
}
var name = extendOptions.name || Super.options.name;
if (process.env.NODE_ENV !== 'production') {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characaters and the hyphen.'
);
}
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// allow further extension
Sub.extend = Super.extend;
// create asset registers, so extended classes
// can have their private assets too.
config._assetTypes.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
// cache constructor
if (isFirstExtend) {
extendOptions._Ctor = Sub;
}
return Sub
};
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
config._assetTypes.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
);
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = Vue.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
created: function created () {
this.cache = Object.create(null);
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
if (vnode && vnode.componentOptions) {
var opts = vnode.componentOptions;
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? opts.Ctor.cid + '::' + opts.tag
: vnode.key;
if (this.cache[key]) {
vnode.child = this.cache[key].child;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this.cache) {
var vnode = this$1.cache[key];
callHook(vnode.child, 'deactivated');
vnode.child.$destroy();
}
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
if (process.env.NODE_ENV !== 'production') {
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
Vue.util = util;
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
Vue.options = Object.create(null);
config._assetTypes.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue$1);
Object.defineProperty(Vue$1.prototype, '$isServer', {
get: function () { return config._isServer; }
});
Vue$1.version = '2.0.5';
/* */
// attributes that should be using props for binding
var mustUseProp = makeMap('value,selected,checked,muted');
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,<th>,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (childNode.child) {
childNode = childNode.child._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while ((parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: child.class
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (staticClass || dynamicClass) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
var res = '';
if (!value) {
return res
}
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (value[i]) {
if ((stringified = stringifyClass(value[i]))) {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML',
xhtml: 'http://www.w3.org/1999/xhtm'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selector = el;
el = document.querySelector(el);
if (!el) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + selector
);
return document.createElement('div')
}
}
return el
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function childNodes (node) {
return node.childNodes
}
function setAttribute (node, key, val) {
node.setAttribute(key, val);
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
childNodes: childNodes,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!key) { return }
var vm = vnode.context;
var ref = vnode.child || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove$1(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key])) {
refs[key].push(ref);
} else {
refs[key] = [ref];
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks$1 = ['create', 'update', 'remove', 'destroy'];
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
vnode1.isComment === vnode2.isComment &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks$1.length; ++i) {
cbs[hooks$1[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); }
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeElement(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeElement (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html
if (parent) {
nodeOps.removeChild(parent, el);
}
}
function createElm (vnode, insertedVnodeQueue, nested) {
var i;
var data = vnode.data;
vnode.isRootInsert = !nested;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode); }
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
initComponent(vnode, insertedVnodeQueue);
return vnode.elm
}
}
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
} else if (vnode.isComment) {
vnode.elm = nodeOps.createComment(vnode.text);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
}
return vnode.elm
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
nodeOps.appendChild(vnode.elm, createElm(children[i], insertedVnodeQueue, true));
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));
}
}
function isPatchable (vnode) {
while (vnode.child) {
vnode = vnode.child._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) { i.create(emptyNode, vnode); }
if (i.insert) { insertedVnodeQueue.push(vnode); }
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
}
vnode.elm = vnode.child.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
var listeners = cbs.remove.length + 1;
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners);
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeElement(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, before;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null;
if (isUndef(idxInOld)) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (vnode.isStatic &&
oldVnode.isStatic &&
vnode.key === oldVnode.key &&
(vnode.isCloned || vnode.isOnce)) {
vnode.elm = oldVnode.elm;
return
}
var i;
var data = vnode.data;
var hasData = isDef(data);
if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var elm = vnode.elm = oldVnode.elm;
var oldCh = oldVnode.children;
var ch = vnode.children;
if (hasData && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (hasData) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var bailed = false;
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
var childNodes = nodeOps.childNodes(elm);
// empty element, allow client to pick up and populate children
if (!childNodes.length) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
var childrenMatch = true;
if (childNodes.length !== children.length) {
childrenMatch = false;
} else {
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!hydrate(childNodes[i$1], children[i$1], insertedVnodeQueue)) {
childrenMatch = false;
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
}
return true
}
function assertNodeMatch (node, vnode) {
if (vnode.tag) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
)
} else {
return _toString(vnode.text) === node.data
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (!vnode) {
if (oldVnode) { invokeDestroyHook(oldVnode); }
return
}
var elm, parent;
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered');
hydrating = true;
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
elm = oldVnode.elm;
parent = nodeOps.parentNode(elm);
createElm(vnode, insertedVnodeQueue);
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm;
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm));
removeVnodes(parent, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (
oldVnode,
vnode
) {
if (!oldVnode.data.directives && !vnode.data.directives) {
return
}
var isCreate = oldVnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
dirsWithInsert.forEach(function (dir) {
callHook$1(dir, 'inserted', vnode, oldVnode);
});
};
if (isCreate) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert');
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {
dirsWithPostpatch.forEach(function (dir) {
callHook$1(dir, 'componentUpdated', vnode, oldVnode);
});
}, 'dir-postpatch');
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode) {
var fn = dir.def && dir.def[hook];
if (fn) {
fn(vnode.elm, dir, vnode, oldVnode);
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
if (!oldVnode.data.attrs && !vnode.data.attrs) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (attrs.__ob__) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
for (key in oldAttrs) {
if (attrs[key] == null) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, key);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticClass && !data.class &&
(!oldData || (!oldData.staticClass && !oldData.class))) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (transitionClass) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
// skip type checking this file because we need to attach private properties
// to elements
function updateDOMListeners (oldVnode, vnode) {
if (!oldVnode.data.on && !vnode.data.on) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
var add = vnode.elm._v_add || (vnode.elm._v_add = function (event, handler, capture) {
vnode.elm.addEventListener(event, handler, capture);
});
var remove = vnode.elm._v_remove || (vnode.elm._v_remove = function (event, handler) {
vnode.elm.removeEventListener(event, handler);
});
updateListeners(on, oldOn, add, remove, vnode.context);
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
function updateDOMProps (oldVnode, vnode) {
if (!oldVnode.data.domProps && !vnode.data.domProps) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (props.__ob__) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (props[key] == null) {
elm[key] = '';
}
}
for (key in props) {
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if ((key === 'textContent' || key === 'innerHTML') && vnode.children) {
vnode.children.length = 0;
}
cur = props[key];
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = cur == null ? '' : String(cur);
if (elm.value !== strCur && !elm.composing) {
elm.value = strCur;
}
} else {
elm[key] = cur;
}
}
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var cssVarRE = /^--/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else {
el.style[normalize(name)] = val;
}
};
var prefixes = ['Webkit', 'Moz', 'ms'];
var testEl;
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div');
prop = camelize(prop);
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper;
if (prefixed in testEl.style) {
return prefixed
}
}
});
function updateStyle (oldVnode, vnode) {
if ((!oldVnode.data || !oldVnode.data.style) && !vnode.data.style) {
return
}
var cur, name;
var el = vnode.elm;
var oldStyle = oldVnode.data.style || {};
var style = vnode.data.style || {};
// handle string
if (typeof style === 'string') {
el.style.cssText = style;
return
}
var needClone = style.__ob__;
// handle array syntax
if (Array.isArray(style)) {
style = vnode.data.style = toObject(style);
}
// clone the style for future updates,
// in case the user mutates the style object in-place.
if (needClone) {
style = vnode.data.style = extend({}, style);
}
for (name in oldStyle) {
if (style[name] == null) {
setProp(el, name, '');
}
}
for (name in style) {
cur = style[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
}
/* */
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
var raf = (inBrowser && window.requestAnimationFrame) || setTimeout;
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls);
addClass(el, cls);
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove$1(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
var transitioneDelays = styles[transitionProp + 'Delay'].split(', ');
var transitionDurations = styles[transitionProp + 'Duration'].split(', ');
var transitionTimeout = getTimeout(transitioneDelays, transitionDurations);
var animationDelays = styles[animationProp + 'Delay'].split(', ');
var animationDurations = styles[animationProp + 'Duration'].split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode) {
var el = vnode.elm;
// call leave callback now
if (el._leaveCb) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return
}
/* istanbul ignore if */
if (el._enterCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var transitionNode = activeInstance.$vnode;
var context = transitionNode && transitionNode.parent
? transitionNode.parent.context
: activeInstance;
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear ? appearClass : enterClass;
var activeClass = isAppear ? appearActiveClass : enterActiveClass;
var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter;
var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter;
var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter;
var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
enterHook &&
// enterHook may be a bound method which exposes
// the length of original fn as _length
(enterHook._length || enterHook.length) > 1;
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
}, 'transition-insert');
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
removeTransitionClass(el, startClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
if (vnode.data.show) {
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (el._enterCb) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return rm()
}
/* istanbul ignore if */
if (el._leaveCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
leave &&
// leave hook may be a bound method which exposes
// the length of original fn as _length
(leave._length || leave.length) > 1;
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
removeTransitionClass(el, leaveClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
leaveClass: (name + "-leave"),
appearClass: (name + "-enter"),
enterActiveClass: (name + "-enter-active"),
leaveActiveClass: (name + "-leave-active"),
appearActiveClass: (name + "-enter-active")
}
});
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn();
}
}
}
var transition = inBrowser ? {
create: function create (_, vnode) {
if (!vnode.data.show) {
enter(vnode);
}
},
remove: function remove (vnode, rm) {
/* istanbul ignore else */
if (!vnode.data.show) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/;
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var model = {
inserted: function inserted (el, binding, vnode) {
if (process.env.NODE_ENV !== 'production') {
if (!modelableTagRE.test(vnode.tag)) {
warn(
"v-model is not supported on element type: <" + (vnode.tag) + ">. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
vnode.context
);
}
}
if (vnode.tag === 'select') {
var cb = function () {
setSelected(el, binding, vnode.context);
};
cb();
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0);
}
} else if (
(vnode.tag === 'textarea' || el.type === 'text') &&
!binding.modifiers.lazy
) {
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options);
if (needReset) {
trigger(el, 'change');
}
}
}
};
function setSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
process.env.NODE_ENV !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.child && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.child._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (value && transition && !isIE9) {
enter(vnode);
}
var originalDisplay = el.style.display === 'none' ? '' : el.style.display;
el.style.display = value ? originalDisplay : 'none';
el.__vOriginalDisplay = originalDisplay;
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (transition && !isIE9) {
if (value) {
enter(vnode);
el.style.display = el.__vOriginalDisplay;
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
}
};
var platformDirectives = {
model: model,
show: show
};
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1].fn;
}
return data
}
function placeholder (h, rawChild) {
return /\d-keep-alive$/.test(rawChild.tag)
? h('keep-alive')
: null
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; });
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (process.env.NODE_ENV !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if (process.env.NODE_ENV !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in') {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
var key = child.key = child.key == null || child.isStatic
? ("__v" + (child.tag + this._uid) + "__")
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true;
}
if (oldChild && oldChild.data && oldChild.key !== key) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild.data.transition = extend({}, data);
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
}, key);
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave, key);
mergeVNodeHook(data, 'enterCancelled', performLeave, key);
mergeVNodeHook(oldData, 'delayLeave', function (leave) {
delayedLeave = leave;
}, key);
}
}
return rawChild
}
};
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final disired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else if (process.env.NODE_ENV !== 'production') {
var opts = c.componentOptions;
var name = opts
? (opts.Ctor.options.name || opts.tag)
: c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || (this.name + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
var f = document.body.offsetHeight; // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
addTransitionClass(el, moveClass);
var info = getTransitionInfo(el);
removeTransitionClass(el, moveClass);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue$1.config.isUnknownElement = isUnknownElement;
Vue$1.config.isReservedTag = isReservedTag;
Vue$1.config.getTagNamespace = getTagNamespace;
Vue$1.config.mustUseProp = mustUseProp;
// install platform runtime directives & components
extend(Vue$1.options.directives, platformDirectives);
extend(Vue$1.options.components, platformComponents);
// install platform patch function
Vue$1.prototype.__patch__ = config._isServer ? noop : patch$1;
// wrap mount
Vue$1.prototype.$mount = function (
el,
hydrating
) {
el = el && !config._isServer ? query(el) : undefined;
return this._mount(el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$1);
} else if (
process.env.NODE_ENV !== 'production' &&
inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)
) {
console.log(
'Download the Vue Devtools for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
}, 0);
return Vue$1;
})));
|
src/main.js | bhuvanmalik007/bhuvanmalik | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import CoreProvider from './core/coreprovider'
import '../node_modules/grommet/grommet-hpinc.min.css'
import './main.css'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.__INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes').default(store)
ReactDOM.render(
<CoreProvider store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
console.error(error)
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
src/components/CheckboxFilter.js | NuCivic/react-dashboard | import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseFilter from './BaseFilter';
import ReactSelect from './ReactSelect';
export default class CheckboxFilter extends BaseFilter {
constructor(props) {
super(props);
this.state.checked = this.state.checked || false;
this.state.value = (this.state.checked) ? this.props.value : null;
this.state.actionType = 'AUTOCOMPLETE_CHANGE';
}
onClick () {
let checked = !this.state.checked; // toggle checked state
let payload;
this.setState({ checked: checked });
if (checked) {
payload = [{label: this.props.label, value: this.props.value}];
} else {
payload = []; // pass empty payload value to reset filter
}
this.onChange(payload);
}
render(){
let val = this.getFilterValue();
return (
<span className='react-dash-checkbox'>
<input
type="checkbox"
name={this.props.name}
value={this.state.checked}
checked={this.state.checked}
disabled={this.isDisabled()}
onClick={this.onClick.bind(this)}
/>
<label htmlFor={this.props.name} value={this.props.label}>
{this.props.label}
</label>
</span>
);
}
}
Registry.set('CheckboxFilter', CheckboxFilter);
|
docs/src/pages/customization/themes/DarkTheme.js | Kagami/material-ui | import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import WithTheme from './WithTheme';
const theme = createMuiTheme({
palette: {
type: 'dark', // Switching the dark mode on is a single property value change.
},
typography: { useNextVariants: true },
});
function DarkTheme() {
return (
<MuiThemeProvider theme={theme}>
<WithTheme />
</MuiThemeProvider>
);
}
export default DarkTheme;
|
src/client/components/JumbotronMetaAreaWidget/JumbotronMetaAreaWidget.js | vidaaudrey/trippian | import log from '../../log'
import React from 'react'
import {
Link
}
from 'react-router'
import {
ContactButtonWidget, StarRatingWidget
}
from '../index'
import {
photos as appConfig
}
from '../../config/appConfig'
import {
UserLinkWidget
}
from '../index'
// use for trip page, pass below: isTripPage = true, title(trip's title)
//for user and trip
const JumbotronMetaAreaWidget = ({
isTripPage = false, isContact = true, title = '', user
}) => {
log.info('inside JumbotronMetaAreaWidget', user)
const {
trippian, name, email, id, facebookId, googleId, picture = appConfig.defaultAvatar,
location, mobile, slogan, website = '', averageRating
} = user
return (
<div className="full-length-container jumbotron-meta-area-widget">
<div className="container">
<div className="col-sm-12 col-md-8 col-md-offset-2">
<div className="circle-image avatar col-sm-3 col-md-3">
<Link to={`trippian/${id}`}> <img src={picture} alt="" /></Link>
</div>
<div className="meta-info meta-info-right col-sm-8 col-md-8">
<div className="col-sm-9 col-md-9 left
">
{isTripPage && <h3>{title}</h3>}
{!isTripPage && <h3>{name}</h3>}
<UserLinkWidget {...user}/>
<span className="text-intro">
{slogan}
</span>
<StarRatingWidget stars={averageRating} />
</div>
{isContact && <div className="col-sm-3 col-md-3"><ContactButtonWidget to={`trippian/${id}/contact`} name={name} /></div> }
</div>
</div>
</div>
</div>
)
}
JumbotronMetaAreaWidget.displayName = 'JumbotronMetaAreaWidget'
export default JumbotronMetaAreaWidget
|
src/components/ui/Card.js | yursky/recommend | /**
* Cards
*
<Card></Card>
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Card } from 'react-native-elements';
// Consts and Libs
import { AppSizes, AppColors, AppStyles } from '@theme/';
/* Component ==================================================================== */
class CustomCard extends Component {
static propTypes = {
containerStyle: PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({}),
]),
titleStyle: PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({}),
]),
}
static defaultProps = {
containerStyle: [],
titleStyle: [],
}
cardProps = () => {
// Defaults
const props = {
dividerStyle: [{
backgroundColor: AppColors.border,
}],
...this.props,
containerStyle: [{
backgroundColor: AppColors.cardBackground,
borderRadius: AppSizes.borderRadius,
borderColor: AppColors.border,
}],
titleStyle: [
AppStyles.h2,
{ marginBottom: 15 },
],
};
if (this.props.containerStyle) {
props.containerStyle.push(this.props.containerStyle);
}
if (this.props.titleStyle) {
props.titleStyle.push(this.props.titleStyle);
}
return props;
}
render = () => <Card {...this.cardProps()} />
}
/* Export Component ==================================================================== */
export default CustomCard;
|
src/routes/User/Register.js | ascrutae/sky-walking-ui | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd';
import styles from './Register.less';
const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;
const passwordStatusMap = {
ok: <div className={styles.success}>强度:强</div>,
pass: <div className={styles.warning}>强度:中</div>,
poor: <div className={styles.error}>强度:太短</div>,
};
const passwordProgressMap = {
ok: 'success',
pass: 'normal',
poor: 'exception',
};
@connect(({ register, loading }) => ({
register,
submitting: loading.effects['register/submit'],
}))
@Form.create()
export default class Register extends Component {
state = {
count: 0,
confirmDirty: false,
visible: false,
help: '',
prefix: '86',
};
componentWillReceiveProps(nextProps) {
const account = this.props.form.getFieldValue('mail');
if (nextProps.register.status === 'ok') {
this.props.dispatch(routerRedux.push({
pathname: '/user/register-result',
state: {
account,
},
}));
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
onGetCaptcha = () => {
let count = 59;
this.setState({ count });
this.interval = setInterval(() => {
count -= 1;
this.setState({ count });
if (count === 0) {
clearInterval(this.interval);
}
}, 1000);
};
getPasswordStatus = () => {
const { form } = this.props;
const value = form.getFieldValue('password');
if (value && value.length > 9) {
return 'ok';
}
if (value && value.length > 5) {
return 'pass';
}
return 'poor';
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields({ force: true }, (err, values) => {
if (!err) {
this.props.dispatch({
type: 'register/submit',
payload: {
...values,
prefix: this.state.prefix,
},
});
}
});
};
handleConfirmBlur = (e) => {
const { value } = e.target;
this.setState({ confirmDirty: this.state.confirmDirty || !!value });
};
checkConfirm = (rule, value, callback) => {
const { form } = this.props;
if (value && value !== form.getFieldValue('password')) {
callback('两次输入的密码不匹配!');
} else {
callback();
}
};
checkPassword = (rule, value, callback) => {
if (!value) {
this.setState({
help: '请输入密码!',
visible: !!value,
});
callback('error');
} else {
this.setState({
help: '',
});
if (!this.state.visible) {
this.setState({
visible: !!value,
});
}
if (value.length < 6) {
callback('error');
} else {
const { form } = this.props;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
}
}
};
changePrefix = (value) => {
this.setState({
prefix: value,
});
};
renderPasswordProgress = () => {
const { form } = this.props;
const value = form.getFieldValue('password');
const passwordStatus = this.getPasswordStatus();
return value && value.length ? (
<div className={styles[`progress-${passwordStatus}`]}>
<Progress
status={passwordProgressMap[passwordStatus]}
className={styles.progress}
strokeWidth={6}
percent={value.length * 10 > 100 ? 100 : value.length * 10}
showInfo={false}
/>
</div>
) : null;
};
render() {
const { form, submitting } = this.props;
const { getFieldDecorator } = form;
const { count, prefix } = this.state;
return (
<div className={styles.main}>
<h3>注册</h3>
<Form onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator('mail', {
rules: [
{
required: true,
message: '请输入邮箱地址!',
},
{
type: 'email',
message: '邮箱地址格式错误!',
},
],
})(<Input size="large" placeholder="邮箱" />)}
</FormItem>
<FormItem help={this.state.help}>
<Popover
content={
<div style={{ padding: '4px 0' }}>
{passwordStatusMap[this.getPasswordStatus()]}
{this.renderPasswordProgress()}
<div style={{ marginTop: 10 }}>
请至少输入 6 个字符。请不要使用容易被猜到的密码。
</div>
</div>
}
overlayStyle={{ width: 240 }}
placement="right"
visible={this.state.visible}
>
{getFieldDecorator('password', {
rules: [
{
validator: this.checkPassword,
},
],
})(
<Input
size="large"
type="password"
placeholder="至少6位密码,区分大小写"
/>
)}
</Popover>
</FormItem>
<FormItem>
{getFieldDecorator('confirm', {
rules: [
{
required: true,
message: '请确认密码!',
},
{
validator: this.checkConfirm,
},
],
})(<Input size="large" type="password" placeholder="确认密码" />)}
</FormItem>
<FormItem>
<InputGroup compact>
<Select
size="large"
value={prefix}
onChange={this.changePrefix}
style={{ width: '20%' }}
>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
{getFieldDecorator('mobile', {
rules: [
{
required: true,
message: '请输入手机号!',
},
{
pattern: /^1\d{10}$/,
message: '手机号格式错误!',
},
],
})(
<Input
size="large"
style={{ width: '80%' }}
placeholder="11位手机号"
/>
)}
</InputGroup>
</FormItem>
<FormItem>
<Row gutter={8}>
<Col span={16}>
{getFieldDecorator('captcha', {
rules: [
{
required: true,
message: '请输入验证码!',
},
],
})(<Input size="large" placeholder="验证码" />)}
</Col>
<Col span={8}>
<Button
size="large"
disabled={count}
className={styles.getCaptcha}
onClick={this.onGetCaptcha}
>
{count ? `${count} s` : '获取验证码'}
</Button>
</Col>
</Row>
</FormItem>
<FormItem>
<Button
size="large"
loading={submitting}
className={styles.submit}
type="primary"
htmlType="submit"
>
注册
</Button>
<Link className={styles.login} to="/user/login">
使用已有账户登录
</Link>
</FormItem>
</Form>
</div>
);
}
}
|
src/svg-icons/av/radio.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRadio = (props) => (
<SvgIcon {...props}>
<path d="M3.24 6.15C2.51 6.43 2 7.17 2 8v12c0 1.1.89 2 2 2h16c1.11 0 2-.9 2-2V8c0-1.11-.89-2-2-2H8.3l8.26-3.34L15.88 1 3.24 6.15zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z"/>
</SvgIcon>
);
AvRadio = pure(AvRadio);
AvRadio.displayName = 'AvRadio';
AvRadio.muiName = 'SvgIcon';
export default AvRadio;
|
modules/IndexRoute.js | egobrightan/react-router | import React from 'react'
import invariant from 'invariant'
import warning from 'warning'
import { createRouteFromReactElement } from './RouteUtils'
import { component, components, falsy } from './PropTypes'
const { bool, func } = React.PropTypes
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
const IndexRoute = React.createClass({
statics: {
createRouteFromReactElement(element, parentRoute) {
if (parentRoute) {
parentRoute.indexRoute = createRouteFromReactElement(element)
} else {
warning(
false,
'An <IndexRoute> does not make sense at the root of your route config'
)
}
}
},
propTypes: {
path: falsy,
ignoreScrollBehavior: bool,
component,
components,
getComponents: func
},
render() {
invariant(
false,
'<IndexRoute> elements are for router configuration only and should not be rendered'
)
}
})
export default IndexRoute
|
ajax/libs/reactive-coffee/0.0.5/reactive-coffee.min.js | tmorin/cdnjs | !function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T={}.hasOwnProperty,U=function(a,b){function c(){this.constructor=a}for(var d in b)T.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},V=[].slice,W=this;"undefined"==typeof exports?this.rx=G={}:G=exports,y=0,x=function(){return y+=1},A=function(a,b){var c;if(!b in a)throw"object has no key "+b;return c=a[b],delete a[b],c},z=function(a,b,c){var d,e,f,g;for(d=f=0,g=a.length;g>f;d=++f)if(e=a[d],c(e)&&(b-=1)<0)return[e,d];return[null,-1]},t=function(a,b){return z(a,0,b)},v=function(){return Object.create(null)},d=G.DepMgr=function(){function a(){this.uid2src={}}return a.prototype.sub=function(a,b){return this.uid2src[a]=b},a.prototype.unsub=function(a){return A(this.uid2src,a)},a}(),G._depMgr=q=new d,e=G.Ev=function(){function a(a){this.inits=a,this.subs=[]}return a.prototype.sub=function(a){var b,c,d,e,f;if(c=x(),null!=this.inits)for(f=this.inits(),d=0,e=f.length;e>d;d++)b=f[d],a(b);return this.subs[c]=a,q.sub(c,this),c},a.prototype.pub=function(a){var b,c,d,e;d=this.subs,e=[];for(c in d)b=d[c],e.push(b(a));return e},a.prototype.unsub=function(a){return A(this.subs,a),q.unsub(a,this)},a.prototype.scoped=function(a,b){var c;c=this.sub(a);try{return b()}finally{this.unsub(c)}},a}(),G.skipFirst=function(a){var b;return b=!0,function(c){return b?b=!1:a(c)}},k=G.Recorder=function(){function a(){this.stack=[],this.isMutating=!1,this.isIgnoring=!1,this.onMutationWarning=new e}return a.prototype.record=function(a,b){var c,d;this.stack.length>0&&!this.isMutating&&_(this.stack).last().addNestedBind(a),this.stack.push(a),d=this.isMutating,this.isMutating=!1,c=this.isIgnoring,this.isIgnoring=!1;try{return b()}finally{this.isIgnoring=c,this.isMutating=d,this.stack.pop()}},a.prototype.sub=function(a){var b,c;return this.stack.length>0&&!this.isIgnoring?(c=_(this.stack).last(),b=a(c)):void 0},a.prototype.addCleanup=function(a){return this.stack.length>0?_(this.stack).last().addCleanup(a):void 0},a.prototype.mutating=function(a){var b;this.stack.length>0&&(console.warn("Mutation to observable detected during a bind context"),this.onMutationWarning.pub(null)),b=this.isMutating,this.isMutating=!0;try{return a()}finally{this.isMutating=b}},a.prototype.ignoring=function(a){var b;b=this.isIgnoring,this.isIgnoring=!0;try{return a()}finally{this.isIgnoring=b}},a}(),G._recorder=F=new k,G.asyncBind=o=function(a,c){var d;return d=new b(c,a),d.refresh(),d},G.bind=p=function(a){return o(null,function(){return this.done(this.record(a))})},G.lagBind=u=function(a,b,c){var d;return d=null,o(b,function(){var b=this;return null!=d&&clearTimeout(d),d=setTimeout(function(){return b.done(b.record(c))},a)})},G.postLagBind=B=function(a,b){var c;return c=null,o(a,function(){var a,d,e,f=this;return e=this.record(b),d=e.val,a=e.ms,null!=c&&clearTimeout(c),c=setTimeout(function(){return f.done(d)},a)})},G.snap=function(a){return F.ignoring(a)},G.onDispose=function(a){return F.addCleanup(a)},G.autoSub=function(a,b){var c;return c=a.sub(b),G.onDispose(function(){return a.unsub(c)}),c},h=G.ObsCell=function(){function a(a){var b,c=this;this.x=a,this.x=null!=(b=this.x)?b:null,this.onSet=new e(function(){return[[null,c.x]]})}return a.prototype.get=function(){var a=this;return F.sub(function(b){return G.autoSub(a.onSet,function(){return b.refresh()})}),this.x},a}(),m=G.SrcCell=function(a){function b(){return P=b.__super__.constructor.apply(this,arguments)}return U(b,a),b.prototype.set=function(a){var b=this;return F.mutating(function(){var c;return b.x!==a?(c=b.x,b.x=a,b.onSet.pub([c,a]),c):void 0})},b}(h),b=G.DepCell=function(a){function b(a,c){this.body=a,b.__super__.constructor.call(this,null!=c?c:null),this.refreshing=!1,this.nestedBinds=[],this.cleanups=[]}return U(b,a),b.prototype.refresh=function(){var a,b,c=this;return this.refreshing?void 0:(b=this.x,a={_recorded:!1,record:function(b){if(!c.refreshing){if(c.disconnect(),c.refreshing=!0,a._recorded)throw"this refresh has already recorded its dependencies";a._recorded=!0;try{return F.record(c,function(){return b.call(a)})}finally{c.refreshing=!1}}},done:function(a){return c.x=a,b!==c.x?c.onSet.pub([b,c.x]):void 0}},this.body.call(a))},b.prototype.disconnect=function(){var a,b,c,d,e,f,g,h;for(g=this.cleanups,c=0,e=g.length;e>c;c++)a=g[c],a();for(h=this.nestedBinds,d=0,f=h.length;f>d;d++)b=h[d],b.disconnect();return this.nestedBinds=[],this.cleanups=[]},b.prototype.addNestedBind=function(a){return this.nestedBinds.push(a)},b.prototype.addCleanup=function(a){return this.cleanups.push(a)},b}(h),g=G.ObsArray=function(){function a(a){var b,c=this;this.xs=a,this.xs=null!=(b=this.xs)?b:[],this.onChange=new e(function(){return[[0,[],c.xs]]})}return a.prototype.all=function(){var a=this;return F.sub(function(b){return G.autoSub(a.onChange,function(){return b.refresh()})}),_.clone(this.xs)},a.prototype.raw=function(){var a=this;return F.sub(function(b){return G.autoSub(a.onChange,function(){return b.refresh()})}),this.xs},a.prototype.at=function(a){var b=this;return F.sub(function(c){return G.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],f=b[1],d=b[2],e===a?c.refresh():void 0})}),this.xs[a]},a.prototype.length=function(){var a=this;return F.sub(function(b){return G.autoSub(a.onChange,function(a){var c,d,e;return d=a[0],e=a[1],c=a[2],e.length!==c.length?b.refresh():void 0})}),this.xs.length},a.prototype.map=function(a){var b;return b=new f,G.autoSub(this.onChange,function(c){var d,e,f;return e=c[0],f=c[1],d=c[2],b.realSplice(e,f.length,d.map(a))}),b},a.prototype.realSplice=function(a,b,c){var d;return d=this.xs.splice.apply(this.xs,[a,b].concat(c)),this.onChange.pub([a,d,c])},a}(),l=G.SrcArray=function(a){function b(){return Q=b.__super__.constructor.apply(this,arguments)}return U(b,a),b.prototype.spliceArray=function(a,b,c){var d=this;return F.mutating(function(){return d.realSplice(a,b,c)})},b.prototype.splice=function(){var a,b,c;return c=arguments[0],b=arguments[1],a=3<=arguments.length?V.call(arguments,2):[],this.spliceArray(c,b,a)},b.prototype.insert=function(a,b){return this.splice(b,0,a)},b.prototype.remove=function(a){return this.removeAt(_(this.raw()).indexOf(a))},b.prototype.removeAt=function(a){return this.splice(a,1)},b.prototype.push=function(a){return this.splice(this.length(),0,a)},b.prototype.put=function(a,b){return this.splice(a,1,b)},b.prototype.replace=function(a){return this.spliceArray(0,this.length(),a)},b}(g),f=G.MappedDepArray=function(a){function b(){return R=b.__super__.constructor.apply(this,arguments)}return U(b,a),b}(g),a=G.DepArray=function(a){function b(a){var c=this;this.f=a,b.__super__.constructor.call(this),G.autoSub(p(function(){return c.f()}).onSet,function(a){var b,d,e,f,g,h,i;return f=a[0],g=a[1],null!=f?(h=t(function(){i=[];for(var a=0,b=Math.min(f.length,g.length);b>=0?b>=a:a>=b;b>=0?a++:a--)i.push(a);return i}.apply(this),function(a){return f[a]!==g[a]}),e=h[0],e=h[1]):e=0,e>-1?(d=null!=f?f.length-e:0,b=g.slice(e),c.realSplice(e,d,b)):void 0})}return U(b,a),b}(g),i=G.ObsMap=function(){function a(a){this.x=null!=a?a:{},this.onAdd=new e(function(){var b,c,d;d=[];for(b in a)c=a[b],d.push([b,c]);return d}),this.onRemove=new e,this.onChange=new e}return a.prototype.get=function(a){var b=this;return F.sub(function(c){return G.autoSub(b.onAdd,function(b){var d,e;return d=b[0],e=b[1],a===d?c.refresh():void 0})}),F.sub(function(c){return G.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],d=b[1],f=b[2],a===e?c.refresh():void 0})}),F.sub(function(c){return G.autoSub(b.onRemove,function(b){var d,e;return e=b[0],d=b[1],a===e?c.refresh():void 0})}),this.x[a]},a.prototype.all=function(){var a=this;return F.sub(function(b){return G.autoSub(a.onAdd,function(){return b.refresh()})}),F.sub(function(b){return G.autoSub(a.onChange,function(){return b.refresh()})}),F.sub(function(b){return G.autoSub(a.onRemove,function(){return b.refresh()})}),_.clone(this.x)},a.prototype.realPut=function(a,b){var c;return a in this.x?(c=this.x[a],this.x[a]=b,this.onChange.pub([a,c,b]),c):(this.x[a]=b,this.onAdd.pub([a,b]),void 0)},a.prototype.realRemove=function(a){var b;return b=A(this.x,a),this.onRemove.pub([a,b]),b},a}(),n=G.SrcMap=function(a){function b(){return S=b.__super__.constructor.apply(this,arguments)}return U(b,a),b.prototype.put=function(a,b){var c=this;return F.mutating(function(){return c.realPut(a,b)})},b.prototype.remove=function(a){var b=this;return F.mutating(function(){return b.realRemove(a)})},b}(i),c=G.DepMap=function(a){function c(a){this.f=a,c.__super__.constructor.call(this),G.autoSub(new b(this.f).onSet,function(a){var b,c,d,e,f;c=a[0],e=a[1];for(b in c)d=c[b],!b in e&&this.realRemove(b);f=[];for(b in e)d=e[b],this.x[b]!==d?f.push(this.realPut(b,d)):f.push(void 0);return f})}return U(c,a),c}(i),G.reactify=function(a,b){var c,d,e,f;return _.isArray(a)?(c=G.array(_.clone(a)),Object.defineProperties(a,_.object(function(){var b,e,f,g;for(f=_.functions(c),g=[],b=0,e=f.length;e>b;b++)d=f[b],"length"!==d&&g.push(function(b){var d,e,f;return d=a[b],e=function(){var e,f,g;return e=1<=arguments.length?V.call(arguments,0):[],null!=d&&(f=d.call.apply(d,[a].concat(V.call(e)))),(g=c[b]).call.apply(g,[c].concat(V.call(e))),f},f={configurable:!0,enumerable:!1,value:e,writable:!0},[b,f]}(d));return g}())),a):Object.defineProperties(a,_.object(function(){var a;a=[];for(e in b)f=b[e],a.push(function(a,b){var c,d,e,f,g;switch(c=null,b.type){case"cell":d=G.cell(null!=(f=b.val)?f:null),c={configurable:!0,enumerable:!0,get:function(){return d.get()},set:function(a){return d.set(a)}};break;case"array":e=G.reactify(null!=(g=b.val)?g:[]),c={configurable:!0,enumerable:!0,get:function(){return e.raw(),e},set:function(a){return e.splice.apply(e,[0,e.length].concat(V.call(a))),e}};break;default:throw"Unknown observable type: "+type}return[a,c]}(e,f));return a}()))},G.autoReactify=function(a){var b,c,d;return G.reactify(a,_.object(function(){var e,f,g,h;for(g=Object.getOwnPropertyNames(a),h=[],e=0,f=g.length;f>e;e++)b=g[e],d=a[b],c=_.isFunction(d)?null:_.isArray(d)?"array":"cell",h.push([b,{type:c,val:d}]);return h}()))},_.extend(G,{cell:function(a){return new m(a)},array:function(a){return new l(a)},map:function(a){return new n(a)}}),G.flatten=function(b){return new a(function(){var a;return _(function(){var c,d,e;for(e=[],c=0,d=b.length;d>c;c++)a=b[c],a instanceof g?e.push(a.raw()):a instanceof h?e.push(a.get()):e.push(a);return e}()).chain().flatten(!0).filter(function(a){return null!=a}).value()})},$.fn.rx=function(a){var b,c,d,e;return d=this.data("rx-map"),null==d&&this.data("rx-map",d=v()),a in d?d[a]:d[a]=function(){var d=this;switch(a){case"focused":return c=G.cell(this.is(":focus")),this.focus(function(){return c.set(!0)}),this.blur(function(){return c.set(!1)}),c;case"val":return e=G.cell(this.val()),this.change(function(){return e.set(d.val())}),this.on("input",function(){return e.set(d.val())}),e;case"checked":return b=G.cell(this.is(":checked")),this.change(function(){return b.set(d.is(":checked"))}),b;default:throw"Unknown reactive property type"}}.call(this)},"undefined"==typeof exports?this.rxt=H={}:H=exports,j=H.RawHtml=function(){function a(a){this.html=a}return a}(),s=["blur","change","click","dblclick","error","focus","focusin","focusout","hover","keydown","keypress","keyup","load","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","ready","resize","scroll","select","submit","toggle","unload"],J=H.specialAttrs={init:function(a,b){return b.call(a)}},M=function(a){return J[a]=function(b,c){return b[a](function(a){return c.call(b,a)})}};for(N=0,O=s.length;O>N;N++)r=s[N],M(r);E=["async","autofocus","checked","location","multiple","readOnly","selected","selectedIndex","tagName","nodeName","nodeType","ownerDocument","defaultChecked","defaultSelected"],D=_.object(function(){var a,b,c;for(c=[],a=0,b=E.length;b>a;a++)C=E[a],c.push([C,null]);return c}()),I=function(a,b,c){return"value"===b?a.val(c):b in D?a.prop(b,c):a.attr(b,c)},H.mktag=w=function(a){return function(b,c){var d,e,f,i,k,l,m,n,o,p;o=null==b&&null==c?[{},null]:null!=c?[b,c]:_.isString(b)||b instanceof j||_.isArray(b)||b instanceof h||b instanceof g?[{},b]:[b,null],d=o[0],e=o[1],f=$("<"+a+"/>"),p=_.omit(d,_.keys(J));for(k in p)n=p[k],n instanceof h?function(a){return G.autoSub(n.onSet,function(b){var c,d;return c=b[0],d=b[1],I(f,a,d)})}(k):I(f,k,n);null!=e&&(l=function(a){var b,c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)if(b=a[d],_.isString(b))f.push(document.createTextNode(b));else if(b instanceof j){if(c=$(b.html),c.length)throw"Cannot insert RawHtml of multiple elements";f.push(c[0])}else{if(!(b instanceof $))throw"Unknown element type in array: "+b.constructor.name;f.push(b[0])}return f},m=function(a){var b;if(f.html(""),!_.isArray(a)){if(_.isString(a)||a instanceof j)return m([a]);throw"Unknown type for contents: "+a.constructor.name}b=l(a),f.append(b)},e instanceof g?G.autoSub(e.onChange,function(a){var b,c,d,e;return c=a[0],d=a[1],b=a[2],f.contents().slice(c,c+d.length).remove(),e=l(b),c===f.contents().length?f.append(e):f.contents().eq(c).before(e)}):e instanceof h?G.autoSub(e.onSet,function(a){var b,c;return b=a[0],c=a[1],m(c)}):m(e));for(i in d)i in J&&J[i](f,d[i],d,e);return f}},L=["html","head","title","base","link","meta","style","script","noscript","body","body","section","nav","article","aside","h1","h2","h3","h4","h5","h6","h1","h6","header","footer","address","main","main","p","hr","pre","blockquote","ol","ul","li","dl","dt","dd","dd","figure","figcaption","div","a","em","strong","small","s","cite","q","dfn","abbr","data","time","code","var","samp","kbd","sub","sup","i","b","u","mark","ruby","rt","rp","bdi","bdo","span","br","wbr","ins","del","img","iframe","embed","object","param","object","video","audio","source","video","audio","track","video","audio","canvas","map","area","area","map","svg","math","table","caption","colgroup","col","tbody","thead","tfoot","tr","td","th","form","fieldset","legend","fieldset","label","input","button","select","datalist","optgroup","option","select","datalist","textarea","keygen","output","progress","meter","details","summary","details","menuitem","menu"],H.tags=_.object(function(){var a,b,c;for(c=[],a=0,b=L.length;b>a;a++)K=L[a],c.push([K,H.mktag(K)]);return c}()),H.rawHtml=function(a){return new j(a)},H.importTags=function(a){return _(null!=a?a:W).extend(H.tags)},H.cast=function(a,b){var c,d,e;return _.object(function(){var f;f=[];for(c in a)e=a[c],d=function(){switch(b[c]){case"array":if(e instanceof G.ObsArray)return e;if(_.isArray(e))return new G.DepArray(function(){return e});if(e instanceof G.ObsCell)return new G.DepArray(function(){return e.get()});throw"Cannot cast to array: "+e.constructor.name;case"cell":return e instanceof G.ObsCell?e:p(function(){return e});default:return e}}(),f.push([c,d]);return f}())},H.cssify=function(a){var b,c;return function(){var d;d=[];for(b in a)c=a[b],null!=c&&d.push(""+_.str.dasherize(b)+": "+(_.isNumber(c)?c+"px":c)+";");return d}().join(" ")}}.call(this); |
ajax/libs/react-redux-form/1.2.2/ReactReduxForm.js | BenjaminVanRyseghem/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("redux"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","redux","react-dom"],t):"object"==typeof exports?exports.ReactReduxForm=t(require("react"),require("redux"),require("react-dom")):e.ReactReduxForm=t(e.React,e.Redux,e["react-dom"])}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){r(46),e.exports=r(46)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={BLUR:"rrf/blur",CHANGE:"rrf/change",FOCUS:"rrf/focus",RESET:"rrf/reset",VALIDATE:"rrf/validate",SET_DIRTY:"rrf/setDirty",SET_ERRORS:"rrf/setErrors",SET_INITIAL:"rrf/setInitial",SET_PENDING:"rrf/setPending",SET_PRISTINE:"rrf/setPristine",SET_SUBMITTED:"rrf/setSubmitted",SET_SUBMIT_FAILED:"rrf/setSubmitFailed",SET_TOUCHED:"rrf/setTouched",SET_UNTOUCHED:"rrf/setUntouched",SET_VALIDITY:"rrf/setValidity",SET_VALIDATING:"rrf/setValidating",SET_FIELDS_VALIDITY:"rrf/setFieldsValidity",SET_VIEW_VALUE:"rrf/setViewValue",RESET_VALIDITY:"rrf/resetValidity",BATCH:"rrf/batch",NULL:"rrf/null"};t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=t;return t.length?((0,f["default"])(n,".")?n=n.slice(0,-1):(0,f["default"])(n,"[]")&&(n=n.slice(0,-2)),(0,a["default"])(e,n,r)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(173),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e){if(!a(e)||d.call(e)!=i||u(e))return!1;var t=o(e);if(null===t)return!0;var r=c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&l.call(r)==s}var o=r(63),u=r(64),a=r(25),i="[object Object]",f=Object.prototype,l=Function.prototype.toString,c=f.hasOwnProperty,s=l.call(Object),d=f.toString;e.exports=n},function(e,t){"use strict";function r(e,t){var r={};return Object.keys(e||{}).forEach(function(n){r[n]=t(e[n],n,e)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(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 u(e,t,r,n){var u=t.length?(0,l["default"])(e,t,d.initialFieldState):e,a=u.hasOwnProperty("$form")?[].concat(o(t),["$form"]):t,f=(0,l["default"])(e,a,d.initialFieldState),c="function"==typeof r?r(f):r;if("$form"in u&&n){var p=(0,s["default"])(u,function(e,t){if("$form"===t)return i["default"].assign(f,c);var r="function"==typeof n?n(e,c):n;return i["default"].assign(e,r)});return t.length?i["default"].setIn(e,t,p):p}return i["default"].setIn(e,a,i["default"].assign(f,c))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(9),i=n(a),f=r(2),l=n(f),c=r(4),s=n(c),d=r(7)},function(e,t){var r=Array.isArray;e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(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 u(e,t){return!t.length&&e.$form?e.$form:(0,d["default"])(e,t,Z)}function a(e,t){return e?e+"."+t:t}function i(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=void 0;if(!(0,_["default"])(t)&&!(0,m["default"])(t))return v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));n=(0,O["default"])(t,function(t,n){return i(a(e,n),t,r)});var o=v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));return v["default"].set(n,"$form",o)}function f(e,t,r){return function(){var n=arguments.length<=0||void 0===arguments[0]?r:arguments[0],o=arguments[1];if(!o.model)return n;var u=(0,T["default"])(o.model);if(t.length&&!(0,y["default"])(u.slice(0,t.length),t))return n;var a=u.slice(t.length);return e(n,o,a)}}function l(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=r.plugins,u=void 0===n?[]:n,a=r.initialFieldState,l=(0,T["default"])(e),c=i(e,t,a),s=u.concat(ee).map(function(e){return f(e,l,c)});return(0,x["default"])(E["default"].apply(void 0,o(s)))}Object.defineProperty(t,"__esModule",{value:!0}),t.initialFieldState=void 0;var c=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};t.getField=u,t["default"]=l;var s=r(2),d=n(s),p=r(9),v=n(p),h=r(47),y=n(h),b=r(3),m=n(b),g=r(6),_=n(g),P=r(4),O=n(P),j=r(19),T=n(j),S=r(96),E=n(S),M=r(29),x=n(M),w=r(84),k=n(w),V=r(91),A=n(V),C=r(88),I=n(C),F=r(85),D=n(F),R=r(90),N=n(R),$=r(89),U=n($),L=r(83),H=n(L),B=r(94),G=n(B),K=r(86),q=n(K),Y=r(93),W=n(Y),z=r(92),J=n(z),Q=r(87),X=n(Q),Z=t.initialFieldState={focus:!1,pending:!1,pristine:!0,submitted:!1,submitFailed:!1,retouched:!1,touched:!1,validating:!1,validated:!1,validity:{},errors:{}},ee=[D["default"],H["default"],G["default"],N["default"],U["default"],k["default"],A["default"],I["default"],q["default"],W["default"],J["default"],X["default"]]},function(t,r){t.exports=e},function(e,t,r){"use strict";function n(e){return null!==e&&(Array.isArray(e)||o(e))}function o(e){return"object"==typeof e&&e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function u(e){for(var t=0,r=e.length,n=Array(r);t<r;t+=1)n[t]=e[t];return n}function a(e){for(var t,r=0,n=Object.keys(e),o=n.length,u={};r<o;r+=1)t=n[r],u[t]=e[t];return u}function i(e){return Array.isArray(e)?u(e):a(e)}function f(e){return n(e)&&(!Object.isFrozen(e),!1)?c(e,[]):e}function l(e){return e}function c(e,t){if(t.some(function(t){return t===e}))throw new Error("object has a reference cycle");return Object.freeze(e),t.push(e),Object.keys(e).forEach(function(r){var o=e[r];n(o)&&c(o,t)}),t.pop(),e}function s(e,t){return(t||[]).reduce(function(e,t){if(e)return e[t]},e)}function d(e,t){return Object.keys(t).reduce(function(e,r){return b.assoc(e,r,t[r])},e)}function p(e,t,r){return null==e||null==t?e:Object.keys(t).reduce(function(e,o){var u=t[o],a=e[o],i=r?r(a,u,o):u;return n(u)&&n(a)?(Object.isFrozen(i)&&Object.isFrozen(a),i===a?e:Array.isArray(u)?b.assoc(e,o,i):v(e,o,p(a,i,r))):v(e,o,i)},e)}function v(e,t,r){return e[t]===r?e:b.assoc(e,t,r)}function h(e,t){var r=t||0,n=e.length;n-=r,n=n<0?0:n;for(var o=new Array(n),u=0;u<n;u+=1)o[u]=e[u+r];return o}function y(e){return h(e,1)}var b=t;t.freeze=function(e){return e},t.thaw=function g(e){if(n(e)&&Object.isFrozen(e)){var t=i(e);return Object.keys(t).forEach(function(e){t[e]=g(t[e])}),t}return e},t.assoc=function(e,t,r){if(e[t]===r)return l(e);var n=i(e);return n[t]=f(r),l(n)},t.set=t.assoc,t.dissoc=function(e,t){var r=i(e);return delete r[t],l(r)},t.unset=t.dissoc,t.assocIn=function _(e,t,r){var n=t[0];return 1===t.length?b.assoc(e,n,r):b.assoc(e,n,_(e[n]||{},t.slice(1),r))},t.setIn=t.assocIn,t.getIn=s,t.updateIn=function(e,t,r){var n=s(e,t);return b.assocIn(e,t,r(n))},["push","unshift","pop","shift","reverse","sort"].forEach(function(e){t[e]=function(t,r){var n=u(t);return n[e](f(r)),l(n)},t[e].displayName="icepick."+e}),t.splice=function(e){var t=u(e),r=y(arguments).map(f);return t.splice.apply(t,r),l(t)},t.slice=function(e,t,r){var n=e.slice(t,r);return l(n)},["map","filter"].forEach(function(e){t[e]=function(t,r){var n=r[e](t);return l(n)},t[e].displayName="icepick."+e}),t.extend=t.assign=function(){var e=y(arguments).reduce(d,arguments[0]);return l(e)},t.merge=p;var m={value:function(){return this.val},thru:function(e){return this.val=f(e(this.val)),this}};Object.keys(t).forEach(function(e){m[e]=function(){var r=h(arguments);return r.unshift(this.val),this.val=t[e].apply(null,r),this}}),t.chain=function(e){var t=Object.create(m);return t.val=e,t},t._weCareAbout=n,t._slice=h},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=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},u=r(43),a=n(u),i=r(73),f=n(i),l=r(42),c=n(l),s=o({},a["default"],f["default"],c["default"]);t["default"]=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(!e)return!0;if(!e.$form){var t=e.errors;return Array.isArray(t)||(0,a["default"])(t)?Object.keys(e.errors).every(function(t){var r=!e.errors[t];return r}):!t}return Object.keys(e).every(function(t){return o(e[t])})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];if(r(e,t))return!0;if("object"!==("undefined"==typeof e?"undefined":u(e))||null===e||"object"!==("undefined"==typeof t?"undefined":u(t))||null===t)return!1;var o=Object.keys(e),i=Object.keys(t);if(o.length!==i.length)return!1;for(var f=0;f<o.length;f++)if(!(n.length&&~n.indexOf(o[f])||a.call(t,o[f])&&r(e[o[f]],t[o[f]])))return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},u="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":"undefined"==typeof e?"undefined":o(e)},a=Object.prototype.hasOwnProperty;t["default"]=n},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e){return null!=e&&u(e.length)&&!o(e)}var o=r(40),u=r(175);e.exports=n},function(e,t,r){function n(e){return"symbol"==typeof e||o(e)&&i.call(e)==u}var o=r(25),u="[object Symbol]",a=Object.prototype,i=a.toString;e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=arguments.length<=2||void 0===arguments[2]?"":arguments[2],n=[],u=null;return Object.keys(e).some(function(o){var a=e[o];return a&&a.$form?""===a.$form.model?Object.keys(a).some(function(e){var n=a[e];return"$form"!==e&&!!n.$form&&!!(0,s["default"])(t,n.$form.model)&&(u=r?[r,o,e].join("."):[o,e].join("."),!0)}):!!(0,s["default"])(t,a.$form.model)&&(u=r?[r,o].join("."):o,!0):((0,l["default"])(a)&&n.push(o),!1)}),u?u:(n.some(function(n){return u=o(e[n],t,r?[r,n].join("."):n),!!u}),u?u:null)}function u(e,t){var r=o(e,t);return r?(0,i["default"])(e,r):null}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormStateKey=o,t["default"]=u;var a=r(2),i=n(a),f=r(3),l=n(f),c=r(104),s=n(c);r(49)},function(e,t){"use strict";function r(e,t){return"function"==typeof e&&t?e(t):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e;return(0,f["default"])(t,".")?t=t.slice(0,-1):(0,f["default"])(t,"[]")&&(t=t.slice(0,-2)),(0,a["default"])(t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(o(e[r][0],t))return r;return-1}var o=r(172);e.exports=n},function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(155);e.exports=n},function(e,t,r){var n=r(62),o=n(Object,"create");e.exports=o},function(e,t,r){function n(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-u?"-0":t}var o=r(16),u=1/0;e.exports=n},function(e,t){function r(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=r},function(e,t){function r(e){return!!e&&"object"==typeof e}e.exports=r},function(e,t,r){var n=r(13),o=r(119),u=r(58),a=r(59),i=r(60),f=r(143),l=r(23),c=i(function(e,t){return null==e?{}:(t=n(u(t,1),l),a(e,o(f(e),t)))});e.exports=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e){return e.displayName||e.name||"Component"}function f(e,t){try{return e.apply(t)}catch(r){return M.value=r,M}}function l(e,t,r){var n=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],l=Boolean(e),d=e||T,v=void 0;v="function"==typeof t?t:t?(0,b["default"])(t):S;var y=r||E,m=n.pure,g=void 0===m||m,_=n.withRef,O=void 0!==_&&_,w=g&&y!==E,k=x++;return function(e){function t(e,t,r){var n=y(e,t,r);return n}var r="Connect("+i(e)+")",n=function(n){function i(e,t){o(this,i);var a=u(this,n.call(this,e,t));a.version=k,a.store=e.store||t.store,(0,j["default"])(a.store,'Could not find "store" in either the context or '+('props of "'+r+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+r+'".'));var f=a.store.getState();return a.state={storeState:f},a.clearCache(),a}return a(i,n),i.prototype.shouldComponentUpdate=function(){return!g||this.haveOwnPropsChanged||this.hasStoreStateChanged},i.prototype.computeStateProps=function(e,t){if(!this.finalMapStateToProps)return this.configureFinalMapState(e,t);var r=e.getState(),n=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(r,t):this.finalMapStateToProps(r);return n},i.prototype.configureFinalMapState=function(e,t){var r=d(e.getState(),t),n="function"==typeof r;return this.finalMapStateToProps=n?r:d,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,n?this.computeStateProps(e,t):r},i.prototype.computeDispatchProps=function(e,t){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(e,t);var r=e.dispatch,n=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(r,t):this.finalMapDispatchToProps(r);return n},i.prototype.configureFinalMapDispatch=function(e,t){var r=v(e.dispatch,t),n="function"==typeof r;return this.finalMapDispatchToProps=n?r:v,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,n?this.computeDispatchProps(e,t):r},i.prototype.updateStatePropsIfNeeded=function(){var e=this.computeStateProps(this.store,this.props);return!(this.stateProps&&(0,h["default"])(e,this.stateProps)||(this.stateProps=e,0))},i.prototype.updateDispatchPropsIfNeeded=function(){var e=this.computeDispatchProps(this.store,this.props);return!(this.dispatchProps&&(0,h["default"])(e,this.dispatchProps)||(this.dispatchProps=e,0))},i.prototype.updateMergedPropsIfNeeded=function(){var e=t(this.stateProps,this.dispatchProps,this.props);return!(this.mergedProps&&w&&(0,h["default"])(e,this.mergedProps)||(this.mergedProps=e,0))},i.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},i.prototype.trySubscribe=function(){l&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},i.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},i.prototype.componentDidMount=function(){this.trySubscribe()},i.prototype.componentWillReceiveProps=function(e){g&&(0,h["default"])(e,this.props)||(this.haveOwnPropsChanged=!0)},i.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},i.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},i.prototype.handleChange=function(){if(this.unsubscribe){var e=this.store.getState(),t=this.state.storeState;if(!g||t!==e){if(g&&!this.doStatePropsDependOnOwnProps){var r=f(this.updateStatePropsIfNeeded,this);if(!r)return;r===M&&(this.statePropsPrecalculationError=M.value),this.haveStatePropsBeenPrecalculated=!0}this.hasStoreStateChanged=!0,this.setState({storeState:e})}}},i.prototype.getWrappedInstance=function(){return(0,j["default"])(O,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},i.prototype.render=function(){var t=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.haveStatePropsBeenPrecalculated,o=this.statePropsPrecalculationError,u=this.renderedElement;if(this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,o)throw o;var a=!0,i=!0;g&&u&&(a=r||t&&this.doStatePropsDependOnOwnProps,i=t&&this.doDispatchPropsDependOnOwnProps);var f=!1,l=!1;n?f=!0:a&&(f=this.updateStatePropsIfNeeded()),i&&(l=this.updateDispatchPropsIfNeeded());var d=!0;return d=!!(f||l||t)&&this.updateMergedPropsIfNeeded(),!d&&u?u:(O?this.renderedElement=(0,s.createElement)(e,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,s.createElement)(e,this.mergedProps),this.renderedElement)},i}(s.Component);return n.displayName=r,n.WrappedComponent=e,n.contextTypes={store:p["default"]},n.propTypes={store:p["default"]},(0,P["default"])(n,e)}}var c=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};t.__esModule=!0,t["default"]=l;var s=r(8),d=r(185),p=n(d),v=r(184),h=n(v),y=r(187),b=n(y),m=r(186),g=(n(m),r(3)),_=(n(g),r(108)),P=n(_),O=r(109),j=n(O),T=function(e){return{}},S=function(e){return{dispatch:e}},E=function(e,t,r){return c({},r,e,t)},M={value:null},x=0},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"string"==typeof e||"number"==typeof e?""+e:""}function u(e){return(0,i["default"])(e.model)?!!e.modelValue&&e.modelValue.some(function(t){return t===e.value}):!!e.modelValue}Object.defineProperty(t,"__esModule",{value:!0});var a=r(51),i=n(a),f=r(9),l=n(f),c=r(10),s=n(c),d={value:function(e){return e.defaultValue||e.hasOwnProperty("value")?e.value:o(e.viewValue)},name:function(e){return e.name||e.model}},p={"default":d,checkbox:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:u(e)},changeAction:function(e){return function(t){var r=e.modelValue,n=e.value;if((0,i["default"])(t)){var o=r||[],u=(o||[]).filter(function(e){return e!==n}),a=u.length===o.length?l["default"].push(o,n):u;return s["default"].change(t,a)}return s["default"].change(t,!r)}}},radio:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:e.modelValue===e.value},value:function(e){return e.value}},select:{name:function(e){return e.name||e.model},value:function(e){return e.modelValue}},text:d,textarea:d,file:{name:function(e){return e.name||e.model}},reset:{onClick:function(e){return function(t){t.preventDefault(),e.dispatch(s["default"].reset(e.model))}}},label:{htmlFor:function(e){return e.htmlFor||e.model}}};t["default"]=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return function(){var r=arguments.length<=0||void 0===arguments[0]?t:arguments[0],n=arguments[1];return n.type===a["default"].BATCH?n.actions.reduce(e,r):e(r,n)}}Object.defineProperty(t,"__esModule",{value:!0});var u=r(1),a=n(u);t["default"]=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return l["default"].setIn(e,t,r)}function u(){var e=arguments.length<=0||void 0===arguments[0]?i["default"]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?o:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){var o=arguments.length<=1||void 0===arguments[1]?r:arguments[1],u=(0,p["default"])(n),a=function(){var r=arguments.length<=0||void 0===arguments[0]?o:arguments[0],n=arguments[1];if(!n.model)return r;var a=(0,p["default"])(n.model);if(!(0,s["default"])(a.slice(0,u.length),u))return r;var i=a.slice(u.length);switch(n.type){case h["default"].CHANGE:case h["default"].LOAD:return i.length?e(r,i)===n.value?r:t(r,i,n.value):n.value;case h["default"].RESET:return i.length?e(r,i)===e(o,i)?r:t(r,i,e(o,i)):o;default:return r}};return(0,b["default"])(a,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModeler=void 0;var a=r(2),i=n(a),f=r(9),l=n(f),c=r(47),s=n(c),d=r(19),p=n(d),v=r(1),h=n(v),y=r(29),b=n(y),m=u();t.createModeler=u,t["default"]=m},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,s["default"])(e,t);if(!t.length)return r;var n=(0,f["default"])(r.$form.model),o=(0,f["default"])(t).slice(n.length),u=(0,a["default"])(r,o,l.initialFieldState);return u&&"$form"in u?u.$form:u?u:l.initialFieldState}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u),i=r(19),f=n(i),l=r(7),c=r(17),s=n(c)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,a["default"])(t);return"function"==typeof e?e(r):(0,f["default"])(e,function(e){return o(e,r)})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(33),a=n(u),i=r(4),f=n(i)},function(e,t){"use strict";function r(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 n(e){return!!(e&&e.stopPropagation&&e.preventDefault)}function o(e){var t=e.target;if(!t){if(!e.nativeEvent)return;return e.nativeEvent.text}return"file"===t.type?[].concat(r(t.files))||t.dataTransfer&&[].concat(r(t.dataTransfer.files)):t.multiple?[].concat(r(t.selectedOptions)).map(function(e){return e.value}):t.value}function u(e){return n(e)?o(e):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return Array.isArray(e)?e:Array.from(e)}function u(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return function(t){var n=e.split(/\[\]\.?/),u=o(n),a=u[0],i=u.slice(1),l=a,s=(0,c["default"])(t,l);return r.forEach(function(e,t){var r=i[t],n=(0,d["default"])(e),o=r?(0,f["default"])(s,n)+"."+r:""+(0,f["default"])(s,n);s=(0,c["default"])(s,o),l+="."+o}),l}}function a(e){return function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return"function"==typeof t?function(r,o){var u=t(o());r(e.apply(void 0,[u].concat(n)))}:e.apply(void 0,[t].concat(n))}}Object.defineProperty(t,"__esModule",{value:!0}),t.trackable=t.track=void 0;var i=r(97),f=n(i),l=r(2),c=n(l),s=r(52),d=n(s);t.track=u,t.trackable=a},function(e,t){function r(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}e.exports=r},function(e,t,r){var n=r(123),o=r(140),u=o(n);e.exports=u},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t,r){var n=r(142),o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")();e.exports=u},function(e,t,r){function n(e,t,r){e=i(e),t=u(t);var n=e.length;r=void 0===r?n:o(a(r),0,n);var f=r;return r-=t.length,r>=0&&e.slice(r,f)==t}var o=r(118),u=r(61),a=r(182),i=r(71);e.exports=n},function(e,t,r){function n(e){var t=o(e)?f.call(e):"";return t==u||t==a}var o=r(24),u="[object Function]",a="[object GeneratorFunction]",i=Object.prototype,f=i.toString;e.exports=n},function(e,r){e.exports=t},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.filter(function(e){return!!e});return r.length?r.length&&r.every(s["default"])?1===r.length?r[0]:{type:i["default"].BATCH,model:e,actions:r}:function(t){var n=(0,l["default"])(r,function(e){return"function"!=typeof e}),o=u(n,2),a=o[0],f=o[1];a.length>1?t({type:i["default"].BATCH,model:e,actions:a}):1===a.length&&t(a[0]),f.forEach(t)}:d}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){var r=[],n=!0,o=!1,u=void 0;try{for(var a,i=e[Symbol.iterator]();!(n=(a=i.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(f){o=!0,u=f}finally{try{!n&&i["return"]&&i["return"]()}finally{if(o)throw u}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(1),i=n(a),f=r(103),l=n(f),c=r(3),s=n(c),d={type:i["default"].NULL};t["default"]={batch:o}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var u=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},a=r(2),i=n(a),f=r(4),l=n(f),c=r(1),s=n(c),d=r(42),p=n(d),v=r(32),h=n(v),y=r(102),b=n(y),m=r(101),g=n(m),_=r(34),P=r(17),O=n(P),j=r(11),T=n(j),S=(0,_.trackable)(function(e){return{type:s["default"].FOCUS,model:e}}),E=(0,_.trackable)(function(e){return{type:s["default"].BLUR,model:e}}),M=(0,_.trackable)(function(e){return{type:s["default"].SET_PRISTINE,model:e}}),x=(0,_.trackable)(function(e){return{type:s["default"].SET_DIRTY,model:e}}),w=(0,_.trackable)(function(e){return{type:s["default"].SET_INITIAL,model:e}}),k=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_PENDING,model:e,pending:t}}),V=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_VALIDATING,model:e,validating:t}}),A=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return o({type:r.errors?s["default"].SET_ERRORS:s["default"].SET_VALIDITY,model:e},r.errors?"errors":"validity",t)}),C=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return{type:s["default"].SET_FIELDS_VALIDITY,model:e,fieldsValidity:t,options:r}}),I=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return A(e,t,u({},r,{errors:!0}))}),F=(0,_.trackable)(function(e,t,r){return C(e,t,u({},r,{errors:!0}))}),D=(0,_.trackable)(function(e){return{type:s["default"].RESET_VALIDITY,model:e}}),R=D,N=(0,_.trackable)(function(e){return{type:s["default"].SET_TOUCHED,model:e}}),$=(0,_.trackable)(function(e){return{type:s["default"].SET_UNTOUCHED,model:e}}),U=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e);r(V(e,!0));var u=function(t){r(A(e,t))},a=t(o,u);"undefined"!=typeof a&&u(a)}}),L=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMITTED,model:e,submitted:t}}),H=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMIT_FAILED,model:e,submitFailed:t}}),B=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){n(k(e,!0));var o=r.fields?F:I;return t.then(function(t){n(p["default"].batch(e,[L(e,!0),A(e,t)]))})["catch"](function(t){n(p["default"].batch(e,[H(e),o(e,t)]))}),t}}),G=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return B(e,t,u({},r,{fields:!0}))}),K=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u))}}),q=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u,{errors:!0}))}}),Y=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n,o){var u=(0,i["default"])(o(),e),a=(0,l["default"])(t,function(e,t){var r=t?(0,i["default"])(u,t):u,n=(0,h["default"])(e,r);return n}),f=r.onValid,c=r.onInvalid;if(f||c){var s=(0,O["default"])(o(),e),d=!(s&&!a.hasOwnProperty(""))||(0,T["default"])(s),p=r.errors?!(0,g["default"])(a):(0,b["default"])(a);f&&d&&p?f():c&&c()}var v=r.errors?F:C;n(v(e,a))}}),W=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return Y(e,t,u({},r,{errors:!0}))});t["default"]={blur:E,focus:S,submit:B,submitFields:G,setDirty:x,setErrors:I,setInitial:w,setPending:k,setValidating:V,setPristine:M,setSubmitted:L,setSubmitFailed:H,setTouched:N,setUntouched:$,setValidity:A,setFieldsValidity:C,setFieldsErrors:F,resetValidity:D,resetErrors:R,validate:K,validateErrors:q,validateFields:Y,validateFieldsErrors:W,asyncSetValidity:U}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function f(e,t){var r=t.model,n=t.mapProps,o=t.getter,u=void 0===o?O["default"]:o,a=t.controlProps,i=void 0===a?(0,A["default"])(t,Object.keys(te)):a;if(!n)return t;var f=(0,G["default"])(r,e),l=(0,H["default"])(e,f);return{model:r,modelValue:u(e,f),fieldValue:l,controlProps:i}}function l(e){return~["radio","checkbox"].indexOf(e.type)}Object.defineProperty(t,"__esModule",{value:!0});var c=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},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),d=r(8),p=r(188),v=r(27),h=n(v),y=r(41),b=r(14),m=n(b),g=r(12),_=n(g),P=r(2),O=n(P),j=r(54),T=n(j),S=r(4),E=n(S),M=r(3),x=n(M),w=r(9),k=n(w),V=r(26),A=n(V),C=r(72),I=n(C),F=r(33),D=n(F),R=r(32),N=n(R),$=r(50),U=n($),L=r(31),H=n(L),B=r(18),G=n(B),K=r(105),q=n(K),Y=r(10),W=n(Y),z=r(11),J=n(z),Q=r(28),X=n(Q),Z=r(78),ee=n(Z),te={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),modelValue:d.PropTypes.any,viewValue:d.PropTypes.any,control:d.PropTypes.any,onLoad:d.PropTypes.func,onSubmit:d.PropTypes.func,fieldValue:d.PropTypes.object,mapProps:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),changeAction:d.PropTypes.func,updateOn:d.PropTypes.string,validateOn:d.PropTypes.string,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidateOn:d.PropTypes.string,asyncValidators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),controlProps:d.PropTypes.object,component:d.PropTypes.any,dispatch:d.PropTypes.func,parser:d.PropTypes.func,formatter:d.PropTypes.func,getter:d.PropTypes.func,
ignore:d.PropTypes.arrayOf(d.PropTypes.string),dynamic:d.PropTypes.bool},re=function(e){function t(e){u(this,t);var r=a(this,Object.getPrototypeOf(t).call(this,e));return r.getChangeAction=r.getChangeAction.bind(r),r.getValidateAction=r.getValidateAction.bind(r),r.handleKeyPress=r.handleKeyPress.bind(r),r.createEventHandler=r.createEventHandler.bind(r),r.handleFocus=r.createEventHandler("focus").bind(r),r.handleBlur=r.createEventHandler("blur").bind(r),r.handleUpdate=r.createEventHandler("change").bind(r),r.handleChange=r.handleChange.bind(r),r.handleLoad=r.handleLoad.bind(r),r.getMappedProps=r.getMappedProps.bind(r),r.attachNode=r.attachNode.bind(r),r.state={viewValue:e.modelValue,mappedProps:{}},r}return i(t,e),s(t,[{key:"componentWillMount",value:function(){var e=this.props,t=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(e,t)})}},{key:"componentDidMount",value:function(){this.attachNode(),this.handleLoad()}},{key:"componentWillReceiveProps",value:function(e){var t=e.mapProps,r=e.modelValue;this.setState({viewValue:r,mappedProps:this.getMappedProps(e,t)})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,I["default"])(this,e,t)}},{key:"componentDidUpdate",value:function(e,t){var r=this.props,n=r.modelValue,o=r.fieldValue,u=r.validateOn,a=r.validators,i=r.errors,f=this.state.viewValue;(a||i)&&o&&!o.validated&&n!==e.modelValue&&"change"===u&&this.validate(),o.focus?document&&document.activeElement!==this.node&&this.node.focus&&this.node.focus():document&&document.activeElement===this.node&&this.node.blur&&this.node.blur(),t.viewValue!==f&&this.updateMappedProps()}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.model,r=e.fieldValue,n=e.dispatch;r&&((0,J["default"])(r)||n(W["default"].resetValidity(t)))}},{key:"getMappedProps",value:function(e,t){var r=this.state.viewValue,n=c({},e,e.controlProps,{onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange,onKeyPress:this.handleKeyPress,viewValue:r});return(0,x["default"])(t)?k["default"].merge(n,(0,E["default"])(t,function(e,t){return"function"==typeof e&&"component"!==t?e(n):e})):t(n)}},{key:"getChangeAction",value:function(e){var t=this.props,r=t.model,n=t.controlProps,o=this.state.mappedProps.changeAction,u=void 0===o?W["default"].change:o,a=l(n)?n.value:e;return u(r,(0,D["default"])(a))}},{key:"getValidateAction",value:function(e){var t=this.props,r=t.validators,n=t.errors,o=t.model,u=t.fieldValue,a=this.getNodeErrors();if(r||n){var i=(0,N["default"])(r,e),f=(0,T["default"])((0,N["default"])(n,e),a),l=r?(0,T["default"])((0,U["default"])(i),f):f;if(!u||!(0,_["default"])(l,u.errors))return W["default"].setErrors(o,l)}else if(a)return W["default"].setErrors(o,a);return!1}},{key:"getAsyncValidateAction",value:function(e){var t=this.props,r=t.asyncValidators,n=t.fieldValue,u=t.model;return!!r&&function(t){return(0,E["default"])(r,function(r,a){return t(W["default"].asyncSetValidity(u,function(t,u){var i=function(e){var t=k["default"].merge(n.validity,o({},a,e));u(t)};r((0,D["default"])(e),i)}))}),e}}},{key:"getNodeErrors",value:function(){var e=this.node;if(!e||!e.willValidate)return null;var t={};return ee["default"].forEach(function(r){t[r]=e.validity[r]}),t}},{key:"updateMappedProps",value:function(){var e=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(this.props,e)})}},{key:"handleChange",value:function(e){this.setState({viewValue:(0,D["default"])(e)}),this.handleUpdate(e)}},{key:"handleKeyPress",value:function(e){"Enter"===e.key&&this.handleSubmit(e)}},{key:"handleLoad",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.controlProps,u=void 0===o?{}:o,a=e.onLoad,i=e.dispatch,f=[],l=void 0;u.hasOwnProperty("defaultValue")?l=u.defaultValue:u.hasOwnProperty("defaultChecked")&&(l=u.defaultChecked),"undefined"!=typeof l?(f.push(this.getValidateAction(l)),f.push(W["default"].change(t,l))):f.push(this.getValidateAction(r)),i(W["default"].batch(t,f)),a&&a(r,n,this.node)}},{key:"handleSubmit",value:function(e){var t=this.props.dispatch;t(this.getChangeAction(e))}},{key:"createEventHandler",value:function(e){var t=this,r=this.props,n=r.dispatch,o=r.model,u=r.updateOn,a=r.validateOn,i=r.asyncValidateOn,f=r.controlProps,c=void 0===f?{}:f,s=r.parser,d=r.ignore,p={focus:W["default"].focus,blur:W["default"].blur}[e],v={focus:c.onFocus,blur:c.onBlur,change:c.onChange}[e],h=function(r){var f=p?[p(o)]:[];a===e&&f.push(t.getValidateAction(r)),i===e&&f.push(t.getAsyncValidateAction(r)),u===e&&f.push(t.getChangeAction(r));var l=f.filter(function(e){return!!e});return l.length&&n(W["default"].batch(o,l)),r};return function(t){return~d.indexOf(e)?v?v(t):t:l(c)?(0,y.compose)(h,(0,q["default"])(v||m["default"]))(t):(0,y.compose)(h,s,D["default"],(0,q["default"])(v||m["default"]))(t)}}},{key:"attachNode",value:function(){var e=(0,p.findDOMNode)(this);e&&(this.node=e)}},{key:"validate",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.validators,u=e.errors,a=e.dispatch;if(!o&&!u)return r;var i=(0,N["default"])(o,r),f=(0,N["default"])(u,r),l=o?(0,T["default"])((0,U["default"])(i),f):f;return(0,_["default"])(l,n.errors)||a(W["default"].setErrors(t,l)),r}},{key:"render",value:function(){var e=this.props,t=e.controlProps,r=void 0===t?{}:t,n=e.component,o=e.control,u=(0,A["default"])(this.state.mappedProps,Object.keys(te));return o?(0,d.cloneElement)(o,c({},u,{onKeyPress:this.handleKeyPress})):(0,d.createElement)(n,c({},r,u,{onKeyPress:this.handleKeyPress}),r.children)}}]),t}(d.Component);re.propTypes=te,re.defaultProps={changeAction:W["default"].change,updateOn:"change",parser:m["default"],formatter:m["default"],controlProps:{},getter:O["default"],ignore:[],dynamic:!1};var ne=(0,h["default"])(f)(re);ne.text=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.text.defaultProps=c({},ne.defaultProps,{component:"input",mapProps:X["default"].text}),ne.radio=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.radio.defaultProps=c({},ne.defaultProps,{component:"input",type:"radio",mapProps:X["default"].radio}),ne.checkbox=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.checkbox.defaultProps=c({},ne.defaultProps,{component:"input",type:"checkbox",mapProps:X["default"].checkbox}),ne.file=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.file.defaultProps=c({},ne.defaultProps,{component:"input",type:"file",mapProps:X["default"].file}),ne.select=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.select.defaultProps=c({},ne.defaultProps,{component:"select",mapProps:X["default"].select}),t["default"]=ne},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?a["default"]:arguments[0];return function(t,r){var n=void 0;try{n=t(void 0,f["default"])}catch(o){n=null}var u=e(r,n);return function(){var e=arguments.length<=0||void 0===arguments[0]?n:arguments[0],r=arguments[1],o=u(e,r);return t(o,r)}}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModelReducerEnhancer=void 0;var u=r(30),a=n(u),i=r(77),f=n(i),l=o(a["default"]);t.createModelReducerEnhancer=o,t["default"]=l},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.track=t.getField=t.utils=t.form=t.batched=t.modeled=t.createFieldClass=t.Errors=t.Form=t.Control=t.Field=t.controls=t.actionTypes=t.actions=t.initialFieldState=t.combineForms=t.modelReducer=t.formReducer=void 0;var u=r(10),a=o(u),i=r(1),f=o(i),l=r(75),c=o(l),s=r(44),d=o(s),p=r(76),v=o(p),h=r(74),y=o(h),b=r(28),m=o(b),g=r(45),_=o(g),P=r(29),O=o(P),j=r(7),T=o(j),S=r(95),E=o(S),M=r(30),x=o(M),w=r(34),k=r(49),V=n(k),A=r(79),C=o(A);t.formReducer=T["default"],t.modelReducer=x["default"],t.combineForms=E["default"],t.initialFieldState=j.initialFieldState,t.actions=a["default"],t.actionTypes=f["default"],t.controls=m["default"],t.Field=c["default"],t.Control=d["default"],t.Form=v["default"],t.Errors=y["default"],t.createFieldClass=l.createFieldClass,t.modeled=_["default"],t.batched=O["default"],t.form=C["default"],t.utils=V,t.getField=j.getField,t.track=w.track},function(e,t){"use strict";function r(e,t){return e&&t&&e.length===t.length&&e.every(function(e,r){return e===t[r]})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=e.children,n=t.children;if(i["default"].Children.count(r)!==i["default"].Children.count(n)||!i["default"].Children.count(r)||!i["default"].Children.count(n))return!0;var o=i["default"].Children.toArray(r),a=i["default"].Children.toArray(n);return[].concat(o).some(function(e,t){var r=a[t];return e.props&&r.props?u(e,r.props,r.state):!(0,s["default"])(e,r)})}function u(e,t,r){return e.props.children?(0,l["default"])(e,t,r)&&o(e.props,t):(0,l["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(8),i=n(a),f=r(72),l=n(f),c=r(12),s=n(c)},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(4),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e,"[]")}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(39),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return function(t){return t===e||Object.keys(e).every(function(r){return e[r]===t[r]})}}function u(e){return function(t){return t&&!!t[e]}}function a(e){return"function"==typeof e?e:null===e?l["default"]:"object"===("undefined"==typeof e?"undefined":i(e))?o(e):u(e)}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=a;var f=r(14),l=n(f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=Array.isArray(e)?a["default"]:f["default"];return r(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(13),a=n(u),i=r(131),f=n(i)},function(e,t){"use strict";function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e){return e&&"object"===("undefined"==typeof e?"undefined":u(e))&&!Array.isArray(e)&&null!==e}function o(e,t){return n(e)&&n(t)&&Object.keys(t).forEach(function(u){n(t[u])?(e[u]||Object.assign(e,r({},u,{})),o(e[u],t[u])):Object.assign(e,r({},u,t[u]))}),e}Object.defineProperty(t,"__esModule",{value:!0});var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=o},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(162),u=r(163),a=r(164),i=r(165),f=r(166);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(38),o=n.Symbol;e.exports=o},function(e,t,r){function n(e,t){var r=a(e)||f(e)||u(e)?o(e.length,String):[],n=r.length,l=!!n;for(var s in e)!t&&!c.call(e,s)||l&&("length"==s||i(s,n))||r.push(s);return r}var o=r(134),u=r(68),a=r(6),i=r(153),f=r(176),l=Object.prototype,c=l.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t,r,a,i){var f=-1,l=e.length;for(r||(r=u),i||(i=[]);++f<l;){var c=e[f];t>0&&r(c)?t>1?n(c,t-1,r,a,i):o(i,c):a||(i[i.length]=c)}return i}var o=r(35),u=r(152);e.exports=n},function(e,t,r){function n(e,t){return e=Object(e),o(e,t,function(t,r){return r in e})}var o=r(132);e.exports=n},function(e,t,r){function n(e,t){return t=u(void 0===t?e.length-1:t,0),function(){for(var r=arguments,n=-1,a=u(r.length-t,0),i=Array(a);++n<a;)i[n]=r[t+n];n=-1;for(var f=Array(t+1);++n<t;)f[n]=r[n];return f[t]=i,o(e,this,f)}}var o=r(114),u=Math.max;e.exports=n},function(e,t,r){function n(e){if("string"==typeof e)return e;if(u(e))return f?f.call(e):"";var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=r(56),u=r(16),a=1/0,i=o?o.prototype:void 0,f=i?i.toString:void 0;e.exports=n},function(e,t,r){function n(e,t){var r=u(e,t);return o(r)?r:void 0}var o=r(128),u=r(146);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function r(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(r){}return t}e.exports=r},function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},function(e,t,r){var n=r(179),o=r(71),u=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,f=n(function(e){e=o(e);var t=[];return u.test(e)&&t.push(""),e.replace(a,function(e,r,n,o){t.push(n?o.replace(i,"$1"):r||e)}),t});e.exports=f},function(e,t){function r(e){for(var t=-1,r=e?e.length:0,n=0,o=[];++t<r;){var u=e[t];u&&(o[n++]=u)}return o}e.exports=r},function(e,t,r){function n(e){return o(e)&&i.call(e,"callee")&&(!l.call(e,"callee")||f.call(e)==u)}var o=r(174),u="[object Arguments]",a=Object.prototype,i=a.hasOwnProperty,f=a.toString,l=a.propertyIsEnumerable;e.exports=n},function(e,t){function r(){return[]}e.exports=r},function(e,t,r){function n(e){return a(e)?o(e,l):i(e)?[e]:u(f(e))}var o=r(13),u=r(138),a=r(6),i=r(16),f=r(66),l=r(23);e.exports=n},function(e,t,r){function n(e){return null==e?"":o(e)}var o=r(61);e.exports=n},function(e,t,r){"use strict";function n(e,t,r){return!o(e.props,t)||!o(e.state,r)}var o=r(107);e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(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 u(){var e=arguments.length<=0||void 0===arguments[0]?O:arguments[0],t=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],o=a({silent:!1,multi:(0,y["default"])(t)},n);return a({type:m["default"].CHANGE,model:t,value:e.getValue(r)},o)},r=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?function(e){return e===r}:arguments[2];return function(u,a){var i=e.get(a(),t,[]),f=i.filter(function(e){return!n(e)}),l=i.length===f.length?[].concat(o(i),[r]):f;u({type:m["default"].CHANGE,model:t,value:l})}},n=function(t){var r=arguments.length<=1||void 0===arguments[1]?null:arguments[1];return function(n,u){var a=e.get(u(),t),i=[].concat(o(a||[]),[r]);n({type:m["default"].CHANGE,model:t,value:i})}},u=function(t){return function(r,n){var o=!e.get(n(),t);r({type:m["default"].CHANGE,model:t,value:o})}},i=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t),a=u.filter(r);n({type:m["default"].CHANGE,model:t,value:a})}},f=function(e){return{type:m["default"].RESET,model:e}},l=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t,[]),a=u.map(r);n({type:m["default"].CHANGE,model:t,value:a})}},s=function(t,r){return function(n,o){var u=e.get(o(),t,[]);n({type:m["default"].CHANGE,model:t,value:e.splice(u,r,1),removeKeys:[r]})}},d=function(t,r,n){return function(o,u){var a=e.get(u(),t,[]);if(r>=a.length||n>=a.length)throw new Error("Error moving array item: invalid bounds "+r+", "+n);var i=a[r],f=e.splice(a,r,1),l=e.splice(f,n,0,i);o({type:m["default"].CHANGE,model:t,value:l})}},p=function(t,r){return function(n,o){var u=e.get(o(),t,{});n({type:m["default"].CHANGE,model:t,value:e.merge(u,r)})}},v=function(t){var r=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return function(n,o){var u=e.get(o(),t,{}),a="string"==typeof r?[r]:r,i=a.reduce(function(t,r){return e.remove(t,r)},u);n({type:m["default"].CHANGE,model:t,value:i,removeKeys:a})}},h=function(e,r){return t(e,r,{silent:!0})};return(0,_["default"])({change:t,filter:i,map:l,merge:p,push:n,remove:s,move:d,reset:f,toggle:u,xor:r,load:h,omit:v},P.trackable)}Object.defineProperty(t,"__esModule",{value:!0});var a=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},i=r(2),f=n(i),l=r(14),c=n(l),s=r(9),d=n(s),p=r(33),v=n(p),h=r(51),y=n(h),b=r(1),m=n(b),g=r(4),_=n(g),P=r(34),O={get:f["default"],getValue:v["default"],splice:d["default"].splice,merge:d["default"].merge,remove:d["default"].dissoc};t["default"]=u()},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e,t){var r=arguments.length<=2||void 0===arguments[2]||arguments[2];return"function"==typeof r?r(e,t):(0,T["default"])(r)||"object"===("undefined"==typeof r?"undefined":c(r))||"string"==typeof r?(0,O["default"])(r)(e):!!r}function f(e,t){var r=t.model,n=(0,I["default"])(r,e),o=(0,k["default"])(e,n).$form,u=(0,A["default"])(e,n);return{model:n,modelValue:(0,y["default"])(e,n),formValue:o,fieldValue:u}}Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},s=r(8),d=n(s),p=r(27),v=n(p),h=r(2),y=n(h),b=r(53),m=n(b),g=r(67),_=n(g),P=r(52),O=n(P),j=r(6),T=n(j),S=r(3),E=n(S),M=r(26),x=n(M),w=r(17),k=n(w),V=r(31),A=n(V),C=r(18),I=n(C),F=r(11),D=n(F),R=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),l(t,[{key:"shouldComponentUpdate",value:function(e){var t=e.fieldValue,r=e.formValue;return t!==this.props.fieldValue||r!==this.props.formValue}},{key:"mapErrorMessages",value:function(e){var t=this,r=this.props.messages;if("string"==typeof e)return this.renderError(e,"error");if(!e)return null;var n=(0,_["default"])((0,m["default"])(e,function(e,n){var o=r[n];if(e){if(o)return t.renderError(o,n);if("string"==typeof e)return t.renderError(e,n);if((0,E["default"])(e))return t.mapErrorMessages(e)}return!1})).reduce(function(e,t){return e.concat(t)},[]);return n.length?n:null}},{key:"renderError",value:function(e,t){var r=this.props,n=r.component,o=r.model,u=r.modelValue,a=r.fieldValue,i=r.fieldValue.errors,f={key:t,model:o,modelValue:u,fieldValue:a},l="function"==typeof e?e(u,i[t]):e;if(!l)return null;var c="function"==typeof n?f:{key:t};return d["default"].createElement(n,c,l)}},{key:"render",value:function(){var e=this.props,r=e.fieldValue,n=e.formValue,o=e.show,u=e.wrapper,a="function"==typeof u?this.props:(0,x["default"])(this.props,Object.keys(t.propTypes));if(!i(r,n,o))return null;var f=(0,D["default"])(r)?null:this.mapErrorMessages(r.errors);return f?d["default"].createElement(u,a,f):null}}]),t}(s.Component);R.propTypes={modelValue:s.PropTypes.any,formValue:s.PropTypes.object,fieldValue:s.PropTypes.object,model:s.PropTypes.string.isRequired,messages:s.PropTypes.objectOf(s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.bool])),show:s.PropTypes.any,wrapper:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),component:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),dispatch:s.PropTypes.func},R.defaultProps={wrapper:"div",component:"span",messages:{},show:!0},t["default"]=(0,v["default"])(f)(R)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e,t){var r=t.model,n=(0,D["default"])(r,e),o=(0,N["default"])(e,n);return{model:r,fieldValue:o}}function f(e,t,r){var n=r.controlPropsMap,o=Object.keys(n).filter(function(t){var r=n[t];return!(!(0,_["default"])(r)||!r.component)&&e.type===r.component});if(o.length)return o[0];try{var u=e.constructor.displayName||e.type.displayName||e.type.name||e.type;return"input"===u&&(u=n[e.props.type]?e.props.type:"text"),n[u]?u:null}catch(a){return}}function l(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r={controlPropsMap:s({},k["default"],e)},n=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),c(t,[{key:"shouldComponentUpdate",value:function(e){var t=this.props.dynamic;return t?(0,A["default"])(this,e):(0,I["default"])(this,e)}},{key:"createControlComponent",value:function(e){var t=this.props;if(!e||!e.props||e instanceof x["default"])return e;var n=f(e,t,r),o=t.mapProps,u=void 0===o?r.controlPropsMap[n]:o,a=(0,O["default"])(t,Object.keys($));return u?p["default"].createElement(x["default"],s({},a,{control:e,controlProps:e.props,component:e.type,mapProps:u})):p["default"].cloneElement(e,null,this.mapChildrenToControl(e.props.children))}},{key:"mapChildrenToControl",value:function(e){var t=this;return p["default"].Children.count(e)>1?p["default"].Children.map(e,function(e){return t.createControlComponent(e)}):this.createControlComponent(e)}},{key:"render",value:function(){var e=this,t=this.props,r=t.component,n=t.children,o=t.fieldValue,u=(0,m["default"])(t,Object.keys($)),a="function"==typeof n?n(o):n;return p["default"].createElement(r,u,p["default"].Children.map(a,function(t){return e.createControlComponent(t)}))}}]),t}(d.Component);return n.propTypes=$,n.defaultProps=s({updateOn:"change",validateOn:"change",asyncValidateOn:"blur",parser:y["default"],changeAction:E["default"].change,dynamic:!1,component:"div"},t),(0,T["default"])(i)(n)}Object.defineProperty(t,"__esModule",{value:!0}),t.createFieldClass=t.controlPropsMap=void 0;var c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=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},d=r(8),p=n(d),v=r(2),h=(n(v),r(14)),y=n(h),b=r(26),m=n(b),g=r(3),_=n(g),P=r(180),O=n(P),j=r(27),T=n(j),S=r(10),E=n(S),M=r(44),x=n(M),w=r(28),k=n(w),V=r(48),A=n(V),C=r(106),I=n(C),F=r(18),D=n(F),R=r(31),N=n(R),$={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]).isRequired,component:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),parser:d.PropTypes.func,updateOn:d.PropTypes.oneOf(["change","blur","focus"]),changeAction:d.PropTypes.func,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidators:d.PropTypes.object,validateOn:d.PropTypes.string,asyncValidateOn:d.PropTypes.string,errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),mapProps:d.PropTypes.func,componentMap:d.PropTypes.object,dynamic:d.PropTypes.bool,dispatch:d.PropTypes.func,getter:d.PropTypes.func,fieldValue:d.PropTypes.object};t.controlPropsMap=k["default"],t.createFieldClass=l,t["default"]=l(k["default"])},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e,t){var r=t.model,n=(0,R["default"])(r,e);return{modelValue:(0,b["default"])(e,n),formValue:(0,F["default"])(e,n)}}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(8),s=n(c),d=r(27),p=n(d),v=r(12),h=n(v),y=r(2),b=n(y),m=r(4),g=n(m),_=r(54),P=n(_),O=r(14),j=n(O),T=r(26),S=n(T),E=r(10),M=n(E),x=r(32),w=n(x),k=r(50),V=n(k),A=r(100),C=n(A),I=r(17),F=n(I),D=r(18),R=n(D),N=r(7),$=r(11),U=n($),L=r(48),H=n(L),B=function(e){function t(e){o(this,t);var r=u(this,Object.getPrototypeOf(t).call(this,e));return r.handleSubmit=r.handleSubmit.bind(r),r.handleReset=r.handleReset.bind(r),r.handleValidSubmit=r.handleValidSubmit.bind(r),r.handleInvalidSubmit=r.handleInvalidSubmit.bind(r),r.attachNode=r.attachNode.bind(r),r}return a(t,e),l(t,[{key:"componentDidMount",value:function(){"change"===this.props.validateOn&&this.validate(this.props,!0)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props.validateOn;"change"===t&&this.validate(e)}},{key:"shouldComponentUpdate",value:function(e){return(0,H["default"])(this,e)}},{key:"attachNode",value:function(e){e&&(this._node=e,this._node.submit=this.handleSubmit)}},{key:"validate",value:function(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],r=this.props,n=r.validators,o=r.errors,u=r.model,a=r.dispatch,i=r.formValue,f=r.modelValue;if(i){if(!n&&!o&&f!==e.modelValue)return void((0,U["default"])(i)||a(M["default"].setValidity(u,!0)));var l=!1,c=(0,g["default"])(n,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).validity;if(!t&&o===u)return a;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),s=(0,g["default"])(o,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).errors;if(!t&&o===u)return(0,N.getField)(i,n).errors;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),d=(0,P["default"])((0,V["default"])(c),s);c.hasOwnProperty("")||s.hasOwnProperty("")||(d[""]=!1),l&&a(M["default"].setFieldsErrors(u,d))}}},{key:"handleValidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model,n=e.modelValue,o=e.onSubmit,u=void 0===o?j["default"]:o;return t(M["default"].setPending(r)),u(n)}},{key:"handleInvalidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model;t(M["default"].setSubmitFailed(r))}},{key:"handleReset",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.dispatch;n(M["default"].reset(r))}},{key:"handleSubmit",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.modelValue,o=t.formValue,u=t.onSubmit,a=t.dispatch,i=t.validators,f=t.errors,l=!o||o.valid;if(!i&&u&&l)return u(n),n;var c={onValid:this.handleValidSubmit,onInvalid:this.handleInvalidSubmit},s=i?(0,P["default"])((0,C["default"])(i),f):f;return a(M["default"].validateFieldsErrors(r,s,c)),n}},{key:"render",value:function(){var e=this.props,r=e.component,n=e.children,o=e.formValue,u=(0,S["default"])(this.props,Object.keys(t.propTypes)),a="function"==typeof n?n(o):n;return s["default"].createElement(r,f({},u,{onSubmit:this.handleSubmit,onReset:this.handleReset,ref:this.attachNode}),a)}}]),t}(c.Component);B.propTypes={component:c.PropTypes.any,validators:c.PropTypes.object,errors:c.PropTypes.object,validateOn:c.PropTypes.oneOf(["change","submit"]),model:c.PropTypes.string.isRequired,modelValue:c.PropTypes.any,formValue:c.PropTypes.object,onSubmit:c.PropTypes.func,dispatch:c.PropTypes.func,children:c.PropTypes.node},B.defaultProps={validateOn:"change",component:"form"},t["default"]=(0,p["default"])(i)(B)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={type:null};t["default"]=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"];t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return u({},e,{get valid(){return(0,i["default"])(e)},get pending(){return(0,l["default"])(e)},get touched(){return(0,s["default"])(e)},get retouched(){return(0,p["default"])(e)}})}Object.defineProperty(t,"__esModule",{value:!0}),t.isRetouched=t.isTouched=t.isPending=t.isValid=void 0;var u=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};t["default"]=o;var a=r(11),i=n(a),f=r(80),l=n(f),c=r(82),s=n(c),d=r(81),p=n(d);t.isValid=i["default"],t.isPending=l["default"],t.isTouched=s["default"],t.isRetouched=p["default"]},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.pending)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.retouched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.touched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].BLUR&&t.type!==a["default"].SET_TOUCHED)return e;var n=(0,c["default"])(e,r).$form;return(0,f["default"])(e,r,function(e){return{focus:t.type!==a["default"].BLUR&&e.focus,touched:!0,retouched:!(!n.submitted&&!n.submitFailed)}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(98),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=void 0,n=t.value,u=t.removeKeys,f=t.silent;if((0,h["default"])(e.value,n))return e;
if(f)return s["default"].set(e,"value",n);if(u){var l=function(){var t=[];return Object.keys(e).forEach(function(r){~u.indexOf(+r)||"$form"===r||(t[r]=e[r])}),{v:i({},(0,g["default"])(t),{$form:e.$form})}}();if("object"===("undefined"==typeof l?"undefined":a(l)))return l.v}if(Array.isArray(n))r=function(e,t){return Array.prototype.map.call(e,t).filter(function(e){return!!e})};else{if(!(0,b["default"])(n))return s["default"].merge(e,{value:n,pristine:!1,validated:!1,retouched:!!e.submitted||e.retouched});r=function(e,t){return(0,P["default"])(e,t)}}var c=r(n,function(t,r){var n=e[r];return!!n&&(Object.hasOwnProperty.call(n,"$form")?o(n,t):(0,h["default"])(t,n.value)?n:s["default"].merge(n,{value:t,pristine:!1,validated:!1,retouched:!!e.submitted||n.retouched}))}),d=s["default"].merge(e.$form||O.initialFieldState,{pristine:!1,validated:!1,retouched:!!e.submitted||(e.$form||O.initialFieldState).retouched});return s["default"].set(c,"$form",s["default"].set(d,"value",n))}function u(e,t,r){if(t.type!==l["default"].CHANGE)return e;var n=(0,p["default"])(e,r,O.initialFieldState),u=o(n,t);return r.length?s["default"].setIn(e,r,u):u}Object.defineProperty(t,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},i=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};t["default"]=u;var f=r(1),l=n(f),c=r(9),s=n(c),d=r(2),p=n(d),v=r(12),h=n(v),y=r(3),b=n(y),m=r(67),g=n(m),_=r(4),P=n(_),O=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].FOCUS?e:(0,f["default"])(e,r,{focus:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PENDING?e:(0,f["default"])(e,r,function(){return{pending:t.pending,submitted:!1,submitFailed:!1,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET&&t.type!==a["default"].SET_INITIAL?e:(0,f["default"])(e,r,l.initialFieldState,l.initialFieldState)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET_VALIDITY?e:(0,f["default"])(e,r,{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors},{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_DIRTY?e:(0,f["default"])(e,r,{pristine:!1})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PRISTINE?e:(0,f["default"])(e,r,{pristine:!0},{pristine:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t,r){var n;if(t.type===s["default"].SET_FIELDS_VALIDITY)return(0,i["default"])(t.fieldsValidity,function(e,r){return l["default"].setValidity(r,e,t.options)}).reduce(function(e,t){return u(e,t,(0,P["default"])(t.model))},e);if(t.type===s["default"].SET_VALIDATING)return(0,g["default"])(e,r,{validating:t.validating,validated:!t.validating});if(t.type!==s["default"].SET_VALIDITY&&t.type!==s["default"].SET_ERRORS)return e;var a=t.type===s["default"].SET_ERRORS,f=a?t.errors:t.validity,c=(0,p["default"])(f)?(0,h["default"])(f,b["default"]):!f;return(0,g["default"])(e,r,(n={},o(n,a?"errors":"validity",f),o(n,a?"validity":"errors",c),o(n,"validating",!1),o(n,"validated",!0),n))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(53),i=n(a),f=r(43),l=n(f),c=r(1),s=n(c),d=r(3),p=n(d),v=r(4),h=n(v),y=r(99),b=n(y),m=r(5),g=n(m),_=r(19),P=n(_)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_SUBMIT_FAILED?e:(0,f["default"])(e,r,function(e){return{pending:!1,submitted:e.submitted&&!t.submitFailed,submitFailed:!!t.submitFailed,touched:!0,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].SET_SUBMITTED)return e;var n=!!t.submitted;return(0,f["default"])(e,r,function(e){return{pending:!1,submitted:n,submitFailed:!n&&e.submitFailed,touched:!0,retouched:!1}},function(e,t){return{submitted:n,submitFailed:!n&&t.submitFailed,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_UNTOUCHED?e:(0,f["default"])(e,r,function(){return{focus:!1,touched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=Object.keys(e),n={},u={},i=a({},h,t),l=i.key,s=i.plugins;return r.forEach(function(t){var r=e[t];if("function"==typeof r){var o=void 0;try{o=r(void 0,v)}catch(a){o=null}n[t]=(0,f["default"])(r,t),u[t]=o}else n[t]=(0,c["default"])(t,r),u[t]=r}),(0,p.combineReducers)(a({},n,o({},l,(0,d["default"])("",u,{plugins:s}))))}Object.defineProperty(t,"__esModule",{value:!0});var a=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};t["default"]=u;var i=r(45),f=n(i),l=r(30),c=n(l),s=r(7),d=n(s),p=r(41),v={type:null},h={key:"forms",plugins:[]}},function(e,t){"use strict";function r(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e,r){return t.reduceRight(function(e,t){return t(e,r)},e)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e,t){var r=void 0;return Object.keys(e).some(function(n){var o=t(e[n],n,e);return!!o&&(r=n,!0)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.slice(0,-1);return r.length?(0,a["default"])(e,r):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u)},function(e,t){"use strict";function r(e){return!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"function"==typeof e?function(t){return!e(t)}:(0,a["default"])(e,o)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(4),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=Array.isArray(e)?f["default"]:c["default"];return(0,a["default"])(e)?t(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(117),f=n(i),l=r(133),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(120),f=n(i)},function(e,t){"use strict";function r(e,t){var r=[[],[]];return e.forEach(function(n,o){t(n,o,e)?r[0].push(n):r[1].push(n)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(e===t)return!0;var r=(0,a["default"])(e),n=(0,a["default"])(t),o=n.every(function(e,t){return r[t]===e});return o}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u)},function(e,t){"use strict";function r(e){return function(t){return t&&t.persist&&t.persist(),e(t),t}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return!(0,i["default"])(e.props,t,["children"])||u.Children.count(e.props.children)!==u.Children.count(t.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(8),a=r(12),i=n(a)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),u=Object.keys(t);if(n.length!==u.length)return!1;for(var a=0;a<n.length;a++)if(!o.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=n},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,u){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var i=0;i<a.length;++i)if(!(r[a[i]]||n[a[i]]||u&&u[a[i]]))try{e[a[i]]=t[a[i]]}catch(f){}}return e}},function(e,t,r){"use strict";var n=function(e,t,r,n,o,u,a,i){if(!e){var f;if(void 0===t)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,o,u,a,i],c=0;f=new Error(t.replace(/%s/g,function(){return l[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}};e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(147),u=r(148),a=r(149),i=r(150),f=r(151);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(157),u=r(158),a=r(159),i=r(160),f=r(161);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(62),o=r(38),u=n(o,"Map");e.exports=u},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.__data__=new o;++t<r;)this.add(e[t])}var o=r(55),u=r(169),a=r(170);n.prototype.add=n.prototype.push=u,n.prototype.has=a,e.exports=n},function(e,t){function r(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)}e.exports=r},function(e,t,r){function n(e,t){var r=e?e.length:0;return!!r&&o(e,t,0)>-1}var o=r(126);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=e?e.length:0;++n<o;)if(r(t,e[n]))return!0;return!1}e.exports=r},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t){function r(e,t,r){return e===e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}e.exports=r},function(e,t,r){function n(e,t,r,n){var s=-1,d=u,p=!0,v=e.length,h=[],y=t.length;if(!v)return h;r&&(t=i(t,f(r))),n?(d=a,p=!1):t.length>=c&&(d=l,p=!1,t=new o(t));e:for(;++s<v;){var b=e[s],m=r?r(b):b;if(b=n||0!==b?b:0,p&&m===m){for(var g=y;g--;)if(t[g]===m)continue e;h.push(b)}else d(t,m,n)||h.push(b)}return h}var o=r(113),u=r(115),a=r(116),i=r(13),f=r(135),l=r(136),c=200;e.exports=n},function(e,t,r){function n(e,t){var r=!0;return o(e,function(e,n,o){return r=!!t(e,n,o)}),r}var o=r(36);e.exports=n},function(e,t){function r(e,t,r,n){for(var o=e.length,u=r+(n?1:-1);n?u--:++u<o;)if(t(e[u],u,e))return u;return-1}e.exports=r},function(e,t,r){var n=r(141),o=n();e.exports=o},function(e,t,r){function n(e,t){return e&&o(e,t,u)}var o=r(122),u=r(177);e.exports=n},function(e,t,r){function n(e,t){t=u(t,e)?[t]:o(t);for(var r=0,n=t.length;null!=e&&r<n;)e=e[a(t[r++])];return r&&r==n?e:void 0}var o=r(137),u=r(154),a=r(23);e.exports=n},function(e,t,r){function n(e,t,r){var n=t(e);return u(e)?n:o(n,r(e))}var o=r(35),u=r(6);e.exports=n},function(e,t,r){function n(e,t,r){if(t!==t)return o(e,u,r);for(var n=r-1,a=e.length;++n<a;)if(e[n]===t)return n;return-1}var o=r(121),u=r(127);e.exports=n},function(e,t){function r(e){return e!==e}e.exports=r},function(e,t,r){function n(e){if(!i(e)||a(e))return!1;var t=o(e)||u(e)?v:c;return t.test(f(e))}var o=r(40),u=r(64),a=r(156),i=r(24),f=r(171),l=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,s=Object.prototype,d=Function.prototype.toString,p=s.hasOwnProperty,v=RegExp("^"+d.call(p).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=n},function(e,t,r){function n(e){if(!o(e))return u(e);var t=[];for(var r in Object(e))i.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(65),u=r(167),a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){if(!o(e))return a(e);var t=u(e),r=[];for(var n in e)("constructor"!=n||!t&&f.call(e,n))&&r.push(n);return r}var o=r(24),u=r(65),a=r(168),i=Object.prototype,f=i.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=-1,n=u(e)?Array(e.length):[];return o(e,function(e,o,u){n[++r]=t(e,o,u)}),n}var o=r(36),u=r(15);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=t.length,u={};++n<o;){var a=t[n],i=e[a];r(i,a)&&(u[a]=i)}return u}e.exports=r},function(e,t,r){function n(e,t){var r;return o(e,function(e,n,o){return r=t(e,n,o),!r}),!!r}var o=r(36);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}e.exports=r},function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},function(e,t){function r(e,t){return e.has(t)}e.exports=r},function(e,t,r){function n(e){return o(e)?e:u(e)}var o=r(6),u=r(66);e.exports=n},function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},function(e,t,r){var n=r(38),o=n["__core-js_shared__"];e.exports=o},function(e,t,r){function n(e,t){return function(r,n){if(null==r)return r;if(!o(r))return e(r,n);for(var u=r.length,a=t?u:-1,i=Object(r);(t?a--:++a<u)&&n(i[a],a,i)!==!1;);return r}}var o=r(15);e.exports=n},function(e,t){function r(e){return function(t,r,n){for(var o=-1,u=Object(t),a=n(t),i=a.length;i--;){var f=a[e?i:++o];if(r(u[f],f,u)===!1)break}return t}}e.exports=r},function(e,t){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,function(){return this}())},function(e,t,r){function n(e){return o(e,a,u)}var o=r(125),u=r(145),a=r(178);e.exports=n},function(e,t,r){var n=r(37),o=r(69),u=Object.getOwnPropertySymbols,a=u?n(u,Object):o;e.exports=a},function(e,t,r){var n=r(35),o=r(63),u=r(144),a=r(69),i=Object.getOwnPropertySymbols,f=i?function(e){for(var t=[];e;)n(t,u(e)),e=o(e);return t}:a;e.exports=f},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t,r){function n(){this.__data__=o?o(null):{}}var o=r(22);e.exports=n},function(e,t){function r(e){return this.has(e)&&delete this.__data__[e]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__;if(o){var r=t[e];return r===u?void 0:r}return i.call(t,e)?t[e]:void 0}var o=r(22),u="__lodash_hash_undefined__",a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){var t=this.__data__;return o?void 0!==t[e]:a.call(t,e)}var o=r(22),u=Object.prototype,a=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__;return r[e]=o&&void 0===t?u:t,this}var o=r(22),u="__lodash_hash_undefined__";e.exports=n},function(e,t,r){function n(e){return a(e)||u(e)||!!(i&&e&&e[i])}var o=r(56),u=r(68),a=r(6),i=o?o.isConcatSpreadable:void 0;e.exports=n},function(e,t){function r(e,t){return t=null==t?n:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=r},function(e,t,r){function n(e,t){if(o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!u(e))||i.test(e)||!a.test(e)||null!=t&&e in Object(t)}var o=r(6),u=r(16),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=n},function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},function(e,t,r){function n(e){return!!u&&u in e}var o=r(139),u=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=n},function(e,t){function r(){this.__data__=[]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():a.call(t,r,1),!0}var o=r(20),u=Array.prototype,a=u.splice;e.exports=n},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r<0?void 0:t[r][1]}var o=r(20);e.exports=n},function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(20);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}var o=r(20);e.exports=n},function(e,t,r){function n(){this.__data__={hash:new o,map:new(a||u),string:new o}}var o=r(110),u=r(111),a=r(112);e.exports=n},function(e,t,r){function n(e){return o(this,e)["delete"](e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e,t){return o(this,e).set(e,t),this}var o=r(21);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.keys,Object);e.exports=o},function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},function(e,t){function r(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=r},function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},function(e,t){function r(e){if(null!=e){try{return n.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var n=Function.prototype.toString;e.exports=r},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(124);e.exports=n},function(e,t,r){function n(e){return u(e)&&o(e)}var o=r(15),u=r(25);e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},function(e,t,r){function n(e){return"string"==typeof e||!o(e)&&u(e)&&f.call(e)==a}var o=r(6),u=r(25),a="[object String]",i=Object.prototype,f=i.toString;e.exports=n},function(e,t,r){function n(e){return a(e)?o(e):u(e)}var o=r(57),u=r(129),a=r(15);e.exports=n},function(e,t,r){function n(e){return a(e)?o(e,!0):u(e)}var o=r(57),u=r(130),a=r(15);e.exports=n},function(e,t,r){function n(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(u);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],u=r.cache;if(u.has(o))return u.get(o);var a=e.apply(this,n);return r.cache=u.set(o,a),a};return r.cache=new(n.Cache||o),r}var o=r(55),u="Expected a function";n.Cache=o,e.exports=n},function(e,t,r){var n=r(13),o=r(58),u=r(59),a=r(60),i=r(23),f=a(function(e,t){return null==e?{}:u(e,n(o(t,1),i))});e.exports=f},function(e,t,r){function n(e){if(!e)return 0===e?e:0;if(e=o(e),e===u||e===-u){var t=e<0?-1:1;return t*a}return e===e?e:0}var o=r(183),u=1/0,a=1.7976931348623157e308;e.exports=n},function(e,t,r){function n(e){var t=o(e),r=t%1;return t===t?r?t-r:t:0}var o=r(181);e.exports=n},function(e,t,r){function n(e){if("number"==typeof e)return e;if(a(e))return i;if(u(e)){var t=o(e.valueOf)?e.valueOf():e;e=u(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(f,"");var r=c.test(e);return r||s.test(e)?d(e.slice(2),r?2:8):l.test(e)?i:+e}var o=r(40),u=r(24),a=r(16),i=NaN,f=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,s=/^0o[0-7]+$/i,d=parseInt;e.exports=n},function(e,t){"use strict";function r(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 o=Object.prototype.hasOwnProperty,u=0;u<r.length;u++)if(!o.call(t,r[u])||e[r[u]]!==t[r[u]])return!1;return!0}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";t.__esModule=!0;var n=r(8);t["default"]=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(e,t){"use strict";function r(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(t){}}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";function n(e){return function(t){return(0,o.bindActionCreators)(e,t)}}t.__esModule=!0,t["default"]=n;var o=r(41)},function(e,t){e.exports=r}])}); |
src/app/components/media/MediaFactCheck.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import { graphql, commitMutation } from 'react-relay/compat';
import { FormattedMessage } from 'react-intl';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import IconReport from '@material-ui/icons/PlaylistAddCheck';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import TimeBefore from '../TimeBefore';
import { parseStringUnixTimestamp } from '../../helpers';
import { can } from '../Can';
import MediaFactCheckField from './MediaFactCheckField';
import ConfirmProceedDialog from '../layout/ConfirmProceedDialog';
const useStyles = makeStyles(() => ({
title: {
fontSize: '16px',
},
}));
const MediaFactCheck = ({ projectMedia }) => {
const classes = useStyles();
const claimDescription = projectMedia.claim_description;
const factCheck = claimDescription ? claimDescription.fact_check : null;
const [title, setTitle] = React.useState(factCheck ? factCheck.title : '');
const [summary, setSummary] = React.useState(factCheck ? factCheck.summary : '');
const [url, setUrl] = React.useState(factCheck ? factCheck.url : '');
const [saving, setSaving] = React.useState(false);
const [showDialog, setShowDialog] = React.useState(false);
const [error, setError] = React.useState(false);
const hasPermission = can(projectMedia.permissions, 'create ClaimDescription') && claimDescription?.description;
const published = (projectMedia.report && projectMedia.report.data && projectMedia.report.data.state === 'published');
const readOnly = projectMedia.is_secondary || projectMedia.suggested_main_item;
const handleGoToReport = () => {
if (!claimDescription) {
setShowDialog(true);
} else {
window.location.assign(`${window.location.pathname.replace(/\/(suggested-matches|similar-media)/, '')}/report`);
}
};
const handleBlur = (field, value) => {
setError(false);
const values = { title, summary, url };
values[field] = value;
if (hasPermission) {
if (factCheck) {
setSaving(true);
commitMutation(Relay.Store, {
mutation: graphql`
mutation MediaFactCheckUpdateFactCheckMutation($input: UpdateFactCheckInput!) {
updateFactCheck(input: $input) {
fact_check {
id
updated_at
title
summary
url
user {
name
}
}
}
}
`,
variables: {
input: {
id: factCheck.id,
...values,
},
},
onCompleted: (response, err) => {
setSaving(false);
if (err) {
setError(true);
} else {
setError(false);
}
},
onError: () => {
setSaving(false);
setError(true);
},
});
} else if (values.title || values.summary || values.url) {
setSaving(true);
commitMutation(Relay.Store, {
mutation: graphql`
mutation MediaFactCheckCreateFactCheckMutation($input: CreateFactCheckInput!) {
createFactCheck(input: $input) {
claim_description {
id
dbid
fact_check {
id
title
summary
url
updated_at
user {
name
}
}
}
}
}
`,
variables: {
input: {
claim_description_id: claimDescription.dbid,
...values,
},
},
onCompleted: (response, err) => {
setSaving(false);
if (err) {
setError(true);
} else {
setError(false);
}
},
onError: () => {
setSaving(false);
setError(true);
},
});
}
}
};
return (
<Box id="media__fact-check">
<Box id="media__fact-check-title" display="flex" alignItems="center" mb={2} justifyContent="space-between">
<Typography className={classes.title} variant="body" component="div">
<strong>
<FormattedMessage id="mediaFactCheck.factCheck" defaultMessage="Fact-check" description="Title of the media fact-check section." />
</strong>
</Typography>
{' '}
<Typography variant="caption" component="div">
{ error ?
<FormattedMessage
id="mediaFactCheck,error"
defaultMessage="error"
description="Caption that informs that a fact-check could not be saved"
/> : null }
{ saving && !error ?
<FormattedMessage
id="mediaFactCheck.saving"
defaultMessage="saving…"
description="Caption that informs that a fact-check is being saved"
/> : null }
{ !saving && !error && factCheck ?
<FormattedMessage
id="mediaFactCheck,saved"
defaultMessage="saved by {userName} {timeAgo}"
values={{
userName: factCheck.user.name,
timeAgo: <TimeBefore date={parseStringUnixTimestamp(factCheck.updated_at)} />,
}}
description="Caption that informs who last saved this fact-check and when it happened."
/> : null }
{ !saving && !factCheck && !error ? <span> </span> : null }
</Typography>
</Box>
<MediaFactCheckField
label={<FormattedMessage id="mediaFactCheck.title" defaultMessage="Title" description="Label for fact-check title field" />}
name="title"
value={title}
onBlur={(newValue) => {
setTitle(newValue);
handleBlur('title', newValue);
}}
hasClaimDescription={Boolean(claimDescription?.description)}
hasPermission={hasPermission}
disabled={readOnly || published}
rows={1}
multiline
/>
<MediaFactCheckField
label={<FormattedMessage id="mediaFactCheck.summary" defaultMessage="Summary" description="Label for fact-check summary field" />}
name="summary"
value={summary}
onBlur={(newValue) => {
setSummary(newValue);
handleBlur('summary', newValue);
}}
hasClaimDescription={Boolean(claimDescription)}
hasPermission={hasPermission}
disabled={readOnly || published}
multiline
/>
<MediaFactCheckField
label={<FormattedMessage id="mediaFactCheck.url" defaultMessage="Published article URL" description="Label for fact-check URL field" />}
name="url"
value={url}
key={url}
onBlur={(newValue) => {
let newUrl = newValue;
if (!/^https?:\/\//.test(newValue)) {
newUrl = `https://${newValue}`;
}
setUrl(newUrl);
handleBlur('url', newUrl);
}}
hasClaimDescription={Boolean(claimDescription)}
hasPermission={hasPermission}
disabled={readOnly || published}
/>
{ projectMedia.team.smooch_bot ?
<Box mt={1}>
<Button
onClick={handleGoToReport}
className="media-fact-check__report-designer"
variant="contained"
color="primary"
startIcon={<IconReport />}
disabled={saving || readOnly}
>
{ published ?
<FormattedMessage
id="mediaActionsBar.publishedReport"
defaultMessage="Published report"
/> :
<FormattedMessage
id="mediaActionsBar.unpublishedReport"
defaultMessage="Unpublished report"
/> }
</Button>
</Box> : null }
<ConfirmProceedDialog
open={showDialog}
title={
<FormattedMessage
id="mediaFactCheck.claimMissingTitle"
defaultMessage="Claim missing"
description="Title of a dialog that is displayed when user attempts to access a report from a fact-check but there is no claim yet"
/>
}
body={
<div>
<Typography variant="body1" component="p" paragraph>
<FormattedMessage
id="mediaFactCheck.claimMissingDesc"
defaultMessage="You must add a claim to access the fact-check report."
description="Content of a dialog that is displayed when user attempts to access a report from a fact-check but there is no claim yet"
/>
</Typography>
</div>
}
proceedLabel={
<FormattedMessage
id="mediaFactCheck.confirmButtonLabel"
defaultMessage="Go back to editing"
/>
}
onProceed={() => { setShowDialog(false); }}
onCancel={() => { setShowDialog(false); }}
/>
</Box>
);
};
MediaFactCheck.defaultProps = {
projectMedia: {
claim_description: null,
team: { smooch_bot: null },
},
};
MediaFactCheck.propTypes = {
projectMedia: PropTypes.shape({
permissions: PropTypes.string,
is_secondary: PropTypes.bool,
team: PropTypes.shape({
smooch_bot: PropTypes.object,
}),
claim_description: PropTypes.shape({
dbid: PropTypes.number,
fact_check: PropTypes.shape({
id: PropTypes.string,
title: PropTypes.string,
summary: PropTypes.string,
url: PropTypes.string,
updated_at: PropTypes.string,
user: PropTypes.shape({
name: PropTypes.string,
}),
}),
}),
}),
};
export default MediaFactCheck;
|
ajax/libs/react-bootstrap-table/3.1.5/react-bootstrap-table.js | pvnr0082t/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom"));
else
root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_6__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SizePerPageDropDown = exports.ButtonGroup = exports.SearchField = exports.ClearSearchButton = exports.ExportCSVButton = exports.ShowSelectedOnlyButton = exports.DeleteButton = exports.InsertButton = exports.InsertModalFooter = exports.InsertModalBody = exports.InsertModalHeader = exports.TableHeaderColumn = exports.BootstrapTable = undefined;
var _BootstrapTable = __webpack_require__(1);
var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable);
var _TableHeaderColumn = __webpack_require__(212);
var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn);
var _InsertModalHeader = __webpack_require__(195);
var _InsertModalHeader2 = _interopRequireDefault(_InsertModalHeader);
var _InsertModalBody = __webpack_require__(197);
var _InsertModalBody2 = _interopRequireDefault(_InsertModalBody);
var _InsertModalFooter = __webpack_require__(196);
var _InsertModalFooter2 = _interopRequireDefault(_InsertModalFooter);
var _InsertButton = __webpack_require__(198);
var _InsertButton2 = _interopRequireDefault(_InsertButton);
var _DeleteButton = __webpack_require__(199);
var _DeleteButton2 = _interopRequireDefault(_DeleteButton);
var _ExportCSVButton = __webpack_require__(200);
var _ExportCSVButton2 = _interopRequireDefault(_ExportCSVButton);
var _ShowSelectedOnlyButton = __webpack_require__(201);
var _ShowSelectedOnlyButton2 = _interopRequireDefault(_ShowSelectedOnlyButton);
var _ClearSearchButton = __webpack_require__(203);
var _ClearSearchButton2 = _interopRequireDefault(_ClearSearchButton);
var _SearchField = __webpack_require__(202);
var _SearchField2 = _interopRequireDefault(_SearchField);
var _ButtonGroup = __webpack_require__(218);
var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup);
var _SizePerPageDropDown = __webpack_require__(182);
var _SizePerPageDropDown2 = _interopRequireDefault(_SizePerPageDropDown);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
if (typeof window !== 'undefined') {
window.BootstrapTable = _BootstrapTable2.default;
window.TableHeaderColumn = _TableHeaderColumn2.default;
window.InsertModalHeader = _InsertModalHeader2.default;
window.InsertModalBody = _InsertModalBody2.default;
window.InsertModalFooter = _InsertModalFooter2.default;
window.InsertButton = _InsertButton2.default;
window.DeleteButton = _DeleteButton2.default;
window.ShowSelectedOnlyButton = _ShowSelectedOnlyButton2.default;
window.ExportCSVButton = _ExportCSVButton2.default;
window.ClearSearchButton = _ClearSearchButton2.default;
window.SearchField = _SearchField2.default;
window.ButtonGroup = _ButtonGroup2.default;
window.SizePerPageDropDown = _SizePerPageDropDown2.default;
}
exports.BootstrapTable = _BootstrapTable2.default;
exports.TableHeaderColumn = _TableHeaderColumn2.default;
exports.InsertModalHeader = _InsertModalHeader2.default;
exports.InsertModalBody = _InsertModalBody2.default;
exports.InsertModalFooter = _InsertModalFooter2.default;
exports.InsertButton = _InsertButton2.default;
exports.DeleteButton = _DeleteButton2.default;
exports.ShowSelectedOnlyButton = _ShowSelectedOnlyButton2.default;
exports.ExportCSVButton = _ExportCSVButton2.default;
exports.ClearSearchButton = _ClearSearchButton2.default;
exports.SearchField = _SearchField2.default;
exports.ButtonGroup = _ButtonGroup2.default;
exports.SizePerPageDropDown = _SizePerPageDropDown2.default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
}();
;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _TableHeader = __webpack_require__(5);
var _TableHeader2 = _interopRequireDefault(_TableHeader);
var _TableBody = __webpack_require__(8);
var _TableBody2 = _interopRequireDefault(_TableBody);
var _PaginationList = __webpack_require__(180);
var _PaginationList2 = _interopRequireDefault(_PaginationList);
var _ToolBar = __webpack_require__(183);
var _ToolBar2 = _interopRequireDefault(_ToolBar);
var _TableFilter = __webpack_require__(204);
var _TableFilter2 = _interopRequireDefault(_TableFilter);
var _TableDataStore = __webpack_require__(205);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
var _csv_export_util = __webpack_require__(206);
var _csv_export_util2 = _interopRequireDefault(_csv_export_util);
var _Filter = __webpack_require__(210);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-alert: 0 */
/* eslint max-len: 0 */
var BootstrapTable = function (_Component) {
_inherits(BootstrapTable, _Component);
function BootstrapTable(props) {
_classCallCheck(this, BootstrapTable);
var _this = _possibleConstructorReturn(this, (BootstrapTable.__proto__ || Object.getPrototypeOf(BootstrapTable)).call(this, props));
_this.handleSort = function () {
return _this.__handleSort__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleExpandRow = function () {
return _this.__handleExpandRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handlePaginationData = function () {
return _this.__handlePaginationData__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleMouseLeave = function () {
return _this.__handleMouseLeave__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleMouseEnter = function () {
return _this.__handleMouseEnter__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowMouseOut = function () {
return _this.__handleRowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowMouseOver = function () {
return _this.__handleRowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleNavigateCell = function () {
return _this.__handleNavigateCell__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowClick = function () {
return _this.__handleRowClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowDoubleClick = function () {
return _this.__handleRowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleSelectAllRow = function () {
return _this.__handleSelectAllRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleShowOnlySelected = function () {
return _this.__handleShowOnlySelected__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleSelectRow = function () {
return _this.__handleSelectRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleAddRow = function () {
return _this.__handleAddRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.getPageByRowKey = function () {
return _this.__getPageByRowKey__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleDropRow = function () {
return _this.__handleDropRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleFilterData = function () {
return _this.__handleFilterData__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleExportCSV = function () {
return _this.__handleExportCSV__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleSearch = function () {
return _this.__handleSearch__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this._scrollTop = function () {
return _this.___scrollTop__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this._scrollHeader = function () {
return _this.___scrollHeader__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.isIE = false;
_this._attachCellEditFunc();
if (_util2.default.canUseDOM()) {
_this.isIE = document.documentMode;
}
_this.store = new _TableDataStore.TableDataStore(_this.props.data ? _this.props.data.slice() : []);
_this.initTable(_this.props);
if (_this.props.selectRow && _this.props.selectRow.selected) {
var copy = _this.props.selectRow.selected.slice();
_this.store.setSelectedRowKey(copy);
}
var currPage = _Const2.default.PAGE_START_INDEX;
if (typeof _this.props.options.page !== 'undefined') {
currPage = _this.props.options.page;
} else if (typeof _this.props.options.pageStartIndex !== 'undefined') {
currPage = _this.props.options.pageStartIndex;
}
_this._adjustHeaderWidth = _this._adjustHeaderWidth.bind(_this);
_this._adjustHeight = _this._adjustHeight.bind(_this);
_this._adjustTable = _this._adjustTable.bind(_this);
_this.state = {
data: _this.getTableData(),
currPage: currPage,
expanding: _this.props.options.expanding || [],
sizePerPage: _this.props.options.sizePerPage || _Const2.default.SIZE_PER_PAGE_LIST[0],
selectedRowKeys: _this.store.getSelectedRowKeys(),
reset: false,
x: _this.props.keyBoardNav ? 0 : -1,
y: _this.props.keyBoardNav ? 0 : -1
};
return _this;
}
_createClass(BootstrapTable, [{
key: 'initTable',
value: function initTable(props) {
var _this2 = this;
var keyField = props.keyField;
var isKeyFieldDefined = typeof keyField === 'string' && keyField.length;
_react2.default.Children.forEach(props.children, function (column) {
if (column.props.isKey) {
if (keyField) {
throw new Error('Error. Multiple key column be detected in TableHeaderColumn.');
}
keyField = column.props.dataField;
}
if (column.props.filter) {
// a column contains a filter
if (!_this2.filter) {
// first time create the filter on the BootstrapTable
_this2.filter = new _Filter.Filter();
}
// pass the filter to column with filter
column.props.filter.emitter = _this2.filter;
}
});
if (this.filter) {
this.filter.removeAllListeners('onFilterChange');
this.filter.on('onFilterChange', function (currentFilter) {
_this2.handleFilterData(currentFilter);
});
}
this.colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) {
prev[curr.name] = curr;
return prev;
}, {});
if (!isKeyFieldDefined && !keyField) {
throw new Error('Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.');
}
this.store.setProps({
isPagination: props.pagination,
keyField: keyField,
colInfos: this.colInfos,
multiColumnSearch: props.multiColumnSearch,
multiColumnSort: props.multiColumnSort,
remote: this.props.remote
});
}
}, {
key: 'getTableData',
value: function getTableData() {
var result = [];
var _props = this.props,
options = _props.options,
pagination = _props.pagination;
var sortName = options.defaultSortName || options.sortName;
var sortOrder = options.defaultSortOrder || options.sortOrder;
var searchText = options.defaultSearch;
if (sortName && sortOrder) {
this.store.setSortInfo(sortOrder, sortName);
this.store.sort();
}
if (searchText) {
this.store.search(searchText);
}
if (pagination) {
var page = void 0;
var sizePerPage = void 0;
if (this.store.isChangedPage()) {
sizePerPage = this.state.sizePerPage;
page = this.state.currPage;
} else {
sizePerPage = options.sizePerPage || _Const2.default.SIZE_PER_PAGE_LIST[0];
page = options.page || 1;
}
result = this.store.page(page, sizePerPage).get();
} else {
result = this.store.get();
}
return result;
}
}, {
key: 'getColumnsDescription',
value: function getColumnsDescription(_ref) {
var children = _ref.children;
var rowCount = 0;
_react2.default.Children.forEach(children, function (column) {
if (Number(column.props.row) > rowCount) {
rowCount = Number(column.props.row);
}
});
return _react2.default.Children.map(children, function (column, i) {
var rowIndex = column.props.row ? Number(column.props.row) : 0;
var rowSpan = column.props.rowSpan ? Number(column.props.rowSpan) : 1;
if (rowSpan + rowIndex === rowCount + 1) {
return {
name: column.props.dataField,
align: column.props.dataAlign,
sort: column.props.dataSort,
format: column.props.dataFormat,
formatExtraData: column.props.formatExtraData,
filterFormatted: column.props.filterFormatted,
filterValue: column.props.filterValue,
editable: column.props.editable,
customEditor: column.props.customEditor,
hidden: column.props.hidden,
hiddenOnInsert: column.props.hiddenOnInsert,
searchable: column.props.searchable,
className: column.props.columnClassName,
editClassName: column.props.editColumnClassName,
invalidEditColumnClassName: column.props.invalidEditColumnClassName,
columnTitle: column.props.columnTitle,
width: column.props.width,
text: column.props.headerText || column.props.children,
sortFunc: column.props.sortFunc,
sortFuncExtraData: column.props.sortFuncExtraData,
export: column.props.export,
expandable: column.props.expandable,
index: i,
attrs: column.props.tdAttr,
style: column.props.tdStyle
};
}
});
}
}, {
key: 'reset',
value: function reset() {
this.store.clean();
this.setState({
data: this.getTableData(),
currPage: 1,
expanding: [],
sizePerPage: _Const2.default.SIZE_PER_PAGE_LIST[0],
selectedRowKeys: this.store.getSelectedRowKeys(),
reset: true
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.initTable(nextProps);
var options = nextProps.options,
selectRow = nextProps.selectRow;
this.store.setData(nextProps.data.slice());
// from #481
var page = this.state.currPage;
if (this.props.options.page !== options.page) {
page = options.page;
}
// from #481
var sizePerPage = this.state.sizePerPage;
if (this.props.options.sizePerPage !== options.sizePerPage) {
sizePerPage = options.sizePerPage;
}
if (this.isRemoteDataSource()) {
var data = nextProps.data.slice();
if (nextProps.pagination && !this.allowRemote(_Const2.default.REMOTE_PAGE)) {
data = this.store.page(page, sizePerPage).get();
}
this.setState({
data: data,
currPage: page,
sizePerPage: sizePerPage,
reset: false
});
} else {
// #125
// remove !options.page for #709
if (page > Math.ceil(nextProps.data.length / sizePerPage)) {
page = 1;
}
var sortList = this.store.getSortInfo();
var sortField = options.sortName;
var sortOrder = options.sortOrder;
if (sortField && sortOrder) {
this.store.setSortInfo(sortOrder, sortField);
this.store.sort();
} else if (sortList.length > 0) {
this.store.sort();
}
var _data = this.store.page(page, sizePerPage).get();
this.setState({
data: _data,
currPage: page,
sizePerPage: sizePerPage,
reset: false
});
}
if (selectRow && selectRow.selected) {
// set default select rows to store.
var copy = selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
this.setState({
selectedRowKeys: copy,
reset: false
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this._adjustTable();
window.addEventListener('resize', this._adjustTable);
this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader);
if (this.props.scrollTop) {
this._scrollTop();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
window.removeEventListener('resize', this._adjustTable);
this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader);
if (this.filter) {
this.filter.removeAllListeners('onFilterChange');
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this._adjustTable();
this._attachCellEditFunc();
if (this.props.options.afterTableComplete) {
this.props.options.afterTableComplete();
}
}
}, {
key: '_attachCellEditFunc',
value: function _attachCellEditFunc() {
var cellEdit = this.props.cellEdit;
if (cellEdit) {
this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this);
if (cellEdit.mode !== _Const2.default.CELL_EDIT_NONE) {
this.props.selectRow.clickToSelect = false;
}
}
}
/**
* Returns true if in the current configuration,
* the datagrid should load its data remotely.
*
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
}, {
key: 'isRemoteDataSource',
value: function isRemoteDataSource(props) {
var _ref2 = props || this.props,
remote = _ref2.remote;
return remote === true || typeof remote === 'function';
}
/**
* Returns true if this action can be handled remote store
* From #990, Sometimes, we need some actions as remote, some actions are handled by default
* so function will tell you the target action is can be handled as remote or not.
* @param {String} [action] Required.
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
}, {
key: 'allowRemote',
value: function allowRemote(action, props) {
var _ref3 = props || this.props,
remote = _ref3.remote;
if (typeof remote === 'function') {
var remoteObj = remote(_Const2.default.REMOTE);
return remoteObj[action];
} else {
return remote;
}
}
}, {
key: 'render',
value: function render() {
var style = {
height: this.props.height,
maxHeight: this.props.maxHeight
};
var columns = this.getColumnsDescription(this.props);
var sortList = this.store.getSortInfo();
var pagination = this.renderPagination();
var toolBar = this.renderToolBar();
var tableFilter = this.renderTableFilter(columns);
var isSelectAll = this.isSelectAll();
var expandColumnOptions = this.props.expandColumnOptions;
if (typeof expandColumnOptions.expandColumnBeforeSelectColumn === 'undefined') {
expandColumnOptions.expandColumnBeforeSelectColumn = true;
}
var colGroups = _util2.default.renderColGroup(columns, this.props.selectRow, expandColumnOptions);
var sortIndicator = this.props.options.sortIndicator;
if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true;
var _props$options$pagina = this.props.options.paginationPosition,
paginationPosition = _props$options$pagina === undefined ? _Const2.default.PAGINATION_POS_BOTTOM : _props$options$pagina;
var showPaginationOnTop = paginationPosition !== _Const2.default.PAGINATION_POS_BOTTOM;
var showPaginationOnBottom = paginationPosition !== _Const2.default.PAGINATION_POS_TOP;
return _react2.default.createElement(
'div',
{ className: (0, _classnames2.default)('react-bs-table-container', this.props.className, this.props.containerClass),
style: this.props.containerStyle },
toolBar,
showPaginationOnTop ? pagination : null,
_react2.default.createElement(
'div',
{ ref: 'table',
className: (0, _classnames2.default)('react-bs-table', this.props.tableContainerClass),
style: _extends({}, style, this.props.tableStyle),
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave },
_react2.default.createElement(
_TableHeader2.default,
{
ref: 'header',
colGroups: colGroups,
headerContainerClass: this.props.headerContainerClass,
tableHeaderClass: this.props.tableHeaderClass,
style: this.props.headerStyle,
rowSelectType: this.props.selectRow.mode,
customComponent: this.props.selectRow.customComponent,
hideSelectColumn: this.props.selectRow.hideSelectColumn,
sortList: sortList,
sortIndicator: sortIndicator,
onSort: this.handleSort,
onSelectAllRow: this.handleSelectAllRow,
bordered: this.props.bordered,
condensed: this.props.condensed,
isFiltered: this.filter ? true : false,
isSelectAll: isSelectAll,
reset: this.state.reset,
expandColumnVisible: expandColumnOptions.expandColumnVisible,
expandColumnComponent: expandColumnOptions.expandColumnComponent,
expandColumnBeforeSelectColumn: expandColumnOptions.expandColumnBeforeSelectColumn },
this.props.children
),
_react2.default.createElement(_TableBody2.default, { ref: 'body',
bodyContainerClass: this.props.bodyContainerClass,
tableBodyClass: this.props.tableBodyClass,
style: _extends({}, style, this.props.bodyStyle),
data: this.state.data,
expandComponent: this.props.expandComponent,
expandableRow: this.props.expandableRow,
expandRowBgColor: this.props.options.expandRowBgColor,
expandBy: this.props.options.expandBy || _Const2.default.EXPAND_BY_ROW,
columns: columns,
trClassName: this.props.trClassName,
striped: this.props.striped,
bordered: this.props.bordered,
hover: this.props.hover,
keyField: this.store.getKeyField(),
condensed: this.props.condensed,
selectRow: this.props.selectRow,
expandColumnOptions: this.props.expandColumnOptions,
cellEdit: this.props.cellEdit,
selectedRowKeys: this.state.selectedRowKeys,
onRowClick: this.handleRowClick,
onRowDoubleClick: this.handleRowDoubleClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
noDataText: this.props.options.noDataText,
withoutNoDataText: this.props.options.withoutNoDataText,
expanding: this.state.expanding,
onExpand: this.handleExpandRow,
beforeShowError: this.props.options.beforeShowError,
keyBoardNav: this.props.keyBoardNav,
onNavigateCell: this.handleNavigateCell,
x: this.state.x,
y: this.state.y })
),
tableFilter,
showPaginationOnBottom ? pagination : null
);
}
}, {
key: 'isSelectAll',
value: function isSelectAll() {
if (this.store.isEmpty()) return false;
var unselectable = this.props.selectRow.unselectable;
var defaultSelectRowKeys = this.store.getSelectedRowKeys();
var allRowKeys = this.store.getAllRowkey();
if (defaultSelectRowKeys.length === 0) return false;
var match = 0;
var noFound = 0;
var unSelectableCnt = 0;
defaultSelectRowKeys.forEach(function (selected) {
if (allRowKeys.indexOf(selected) !== -1) match++;else noFound++;
if (unselectable && unselectable.indexOf(selected) !== -1) unSelectableCnt++;
});
if (noFound === defaultSelectRowKeys.length) return false;
if (match === allRowKeys.length) {
return true;
} else {
if (unselectable && match <= unSelectableCnt && unSelectableCnt === unselectable.length) return false;else return 'indeterminate';
}
// return (match === allRowKeys.length) ? true : 'indeterminate';
}
}, {
key: 'cleanSelected',
value: function cleanSelected() {
this.store.setSelectedRowKey([]);
this.setState({
selectedRowKeys: [],
reset: false
});
}
}, {
key: '__handleSort__REACT_HOT_LOADER__',
value: function __handleSort__REACT_HOT_LOADER__(order, sortField) {
if (this.props.options.onSortChange) {
this.props.options.onSortChange(sortField, order, this.props);
}
this.store.setSortInfo(order, sortField);
if (this.allowRemote(_Const2.default.REMOTE_SORT)) {
return;
}
var result = this.store.sort().get();
this.setState({
data: result,
reset: false
});
}
}, {
key: '__handleExpandRow__REACT_HOT_LOADER__',
value: function __handleExpandRow__REACT_HOT_LOADER__(expanding) {
var _this3 = this;
this.setState({ expanding: expanding, reset: false }, function () {
_this3._adjustHeaderWidth();
});
}
}, {
key: '__handlePaginationData__REACT_HOT_LOADER__',
value: function __handlePaginationData__REACT_HOT_LOADER__(page, sizePerPage) {
var _props$options = this.props.options,
onPageChange = _props$options.onPageChange,
pageStartIndex = _props$options.pageStartIndex;
var emptyTable = this.store.isEmpty();
if (onPageChange) {
onPageChange(page, sizePerPage);
}
var state = {
sizePerPage: sizePerPage,
reset: false
};
if (!emptyTable) state.currPage = page;
this.setState(state);
if (this.allowRemote(_Const2.default.REMOTE_PAGE) || emptyTable) {
return;
}
// We calculate an offset here in order to properly fetch the indexed data,
// despite the page start index not always being 1
var normalizedPage = void 0;
if (pageStartIndex !== undefined) {
var offset = Math.abs(_Const2.default.PAGE_START_INDEX - pageStartIndex);
normalizedPage = page + offset;
} else {
normalizedPage = page;
}
var result = this.store.page(normalizedPage, sizePerPage).get();
this.setState({ data: result, reset: false });
}
}, {
key: '__handleMouseLeave__REACT_HOT_LOADER__',
value: function __handleMouseLeave__REACT_HOT_LOADER__() {
if (this.props.options.onMouseLeave) {
this.props.options.onMouseLeave();
}
}
}, {
key: '__handleMouseEnter__REACT_HOT_LOADER__',
value: function __handleMouseEnter__REACT_HOT_LOADER__() {
if (this.props.options.onMouseEnter) {
this.props.options.onMouseEnter();
}
}
}, {
key: '__handleRowMouseOut__REACT_HOT_LOADER__',
value: function __handleRowMouseOut__REACT_HOT_LOADER__(row, event) {
if (this.props.options.onRowMouseOut) {
this.props.options.onRowMouseOut(row, event);
}
}
}, {
key: '__handleRowMouseOver__REACT_HOT_LOADER__',
value: function __handleRowMouseOver__REACT_HOT_LOADER__(row, event) {
if (this.props.options.onRowMouseOver) {
this.props.options.onRowMouseOver(row, event);
}
}
}, {
key: '__handleNavigateCell__REACT_HOT_LOADER__',
value: function __handleNavigateCell__REACT_HOT_LOADER__(_ref4) {
var offSetX = _ref4.x,
offSetY = _ref4.y,
lastEditCell = _ref4.lastEditCell;
var pagination = this.props.pagination;
var _state = this.state,
x = _state.x,
y = _state.y,
currPage = _state.currPage;
x += offSetX;
y += offSetY;
// currPage += 1;
// console.log(currPage);
var columns = this.store.getColInfos();
var visibleRowSize = this.state.data.length;
var visibleColumnSize = Object.keys(columns).filter(function (k) {
return !columns[k].hidden;
}).length;
if (y >= visibleRowSize) {
currPage++;
var lastPage = pagination ? this.refs.pagination.getLastPage() : -1;
if (currPage <= lastPage) {
this.handlePaginationData(currPage, this.state.sizePerPage);
} else {
return;
}
y = 0;
} else if (y < 0) {
currPage--;
if (currPage > 0) {
this.handlePaginationData(currPage, this.state.sizePerPage);
} else {
return;
}
y = visibleRowSize - 1;
} else if (x >= visibleColumnSize) {
if (y + 1 === visibleRowSize) {
currPage++;
var _lastPage = pagination ? this.refs.pagination.getLastPage() : -1;
if (currPage <= _lastPage) {
this.handlePaginationData(currPage, this.state.sizePerPage);
} else {
return;
}
y = 0;
} else {
y++;
}
x = lastEditCell ? 1 : 0;
} else if (x < 0) {
x = visibleColumnSize - 1;
if (y === 0) {
currPage--;
if (currPage > 0) {
this.handlePaginationData(currPage, this.state.sizePerPage);
} else {
return;
}
y = this.state.sizePerPage - 1;
} else {
y--;
}
}
this.setState({
x: x, y: y, currPage: currPage, reset: false
});
}
}, {
key: '__handleRowClick__REACT_HOT_LOADER__',
value: function __handleRowClick__REACT_HOT_LOADER__(row, rowIndex, cellIndex) {
var _props2 = this.props,
options = _props2.options,
keyBoardNav = _props2.keyBoardNav;
if (options.onRowClick) {
options.onRowClick(row);
}
if (keyBoardNav) {
var _ref5 = (typeof keyBoardNav === 'undefined' ? 'undefined' : _typeof(keyBoardNav)) === 'object' ? keyBoardNav : {},
clickToNav = _ref5.clickToNav;
clickToNav = clickToNav === false ? clickToNav : true;
if (clickToNav) {
this.setState({
x: cellIndex,
y: rowIndex,
reset: false
});
}
}
}
}, {
key: '__handleRowDoubleClick__REACT_HOT_LOADER__',
value: function __handleRowDoubleClick__REACT_HOT_LOADER__(row) {
if (this.props.options.onRowDoubleClick) {
this.props.options.onRowDoubleClick(row);
}
}
}, {
key: '__handleSelectAllRow__REACT_HOT_LOADER__',
value: function __handleSelectAllRow__REACT_HOT_LOADER__(e) {
var isSelected = e.currentTarget.checked;
var keyField = this.store.getKeyField();
var _props$selectRow = this.props.selectRow,
onSelectAll = _props$selectRow.onSelectAll,
unselectable = _props$selectRow.unselectable,
selected = _props$selectRow.selected;
var selectedRowKeys = [];
var result = true;
var rows = isSelected ? this.store.get() : this.store.getRowByKey(this.state.selectedRowKeys);
if (unselectable && unselectable.length > 0) {
if (isSelected) {
rows = rows.filter(function (r) {
return unselectable.indexOf(r[keyField]) === -1 || selected && selected.indexOf(r[keyField]) !== -1;
});
} else {
rows = rows.filter(function (r) {
return unselectable.indexOf(r[keyField]) === -1;
});
}
}
if (onSelectAll) {
result = this.props.selectRow.onSelectAll(isSelected, rows);
}
if (typeof result == 'undefined' || result !== false) {
if (isSelected) {
selectedRowKeys = Array.isArray(result) ? result : rows.map(function (r) {
return r[keyField];
});
} else {
if (unselectable && selected) {
selectedRowKeys = selected.filter(function (r) {
return unselectable.indexOf(r) > -1;
});
}
}
this.store.setSelectedRowKey(selectedRowKeys);
this.setState({ selectedRowKeys: selectedRowKeys, reset: false });
}
}
}, {
key: '__handleShowOnlySelected__REACT_HOT_LOADER__',
value: function __handleShowOnlySelected__REACT_HOT_LOADER__() {
this.store.ignoreNonSelected();
var result = void 0;
if (this.props.pagination) {
result = this.store.page(1, this.state.sizePerPage).get();
} else {
result = this.store.get();
}
this.setState({
data: result,
reset: false,
currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX
});
}
}, {
key: '__handleSelectRow__REACT_HOT_LOADER__',
value: function __handleSelectRow__REACT_HOT_LOADER__(row, isSelected, e) {
var result = true;
var currSelected = this.store.getSelectedRowKeys();
var rowKey = row[this.store.getKeyField()];
var selectRow = this.props.selectRow;
if (selectRow.onSelect) {
result = selectRow.onSelect(row, isSelected, e);
}
if (typeof result === 'undefined' || result !== false) {
if (selectRow.mode === _Const2.default.ROW_SELECT_SINGLE) {
currSelected = isSelected ? [rowKey] : [];
} else {
if (isSelected) {
currSelected.push(rowKey);
} else {
currSelected = currSelected.filter(function (key) {
return rowKey !== key;
});
}
}
this.store.setSelectedRowKey(currSelected);
this.setState({
selectedRowKeys: currSelected,
reset: false
});
}
}
}, {
key: 'handleEditCell',
value: function handleEditCell(newVal, rowIndex, colIndex) {
var onCellEdit = this.props.options.onCellEdit;
var _props$cellEdit = this.props.cellEdit,
beforeSaveCell = _props$cellEdit.beforeSaveCell,
afterSaveCell = _props$cellEdit.afterSaveCell;
var columns = this.getColumnsDescription(this.props);
var fieldName = columns[colIndex].name;
if (beforeSaveCell) {
var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal);
if (!isValid && typeof isValid !== 'undefined') {
this.setState({
data: this.store.get(),
reset: false
});
return;
}
}
if (onCellEdit) {
newVal = onCellEdit(this.state.data[rowIndex], fieldName, newVal);
}
if (this.allowRemote(_Const2.default.REMOTE_CELL_EDIT)) {
if (afterSaveCell) {
afterSaveCell(this.state.data[rowIndex], fieldName, newVal);
}
return;
}
var result = this.store.edit(newVal, rowIndex, fieldName).get();
this.setState({
data: result,
reset: false
});
if (afterSaveCell) {
afterSaveCell(this.state.data[rowIndex], fieldName, newVal);
}
}
}, {
key: 'handleAddRowAtBegin',
value: function handleAddRowAtBegin(newObj) {
try {
this.store.addAtBegin(newObj);
} catch (e) {
return e;
}
this._handleAfterAddingRow(newObj, true);
}
}, {
key: '__handleAddRow__REACT_HOT_LOADER__',
value: function __handleAddRow__REACT_HOT_LOADER__(newObj) {
var onAddRow = this.props.options.onAddRow;
if (onAddRow) {
var colInfos = this.store.getColInfos();
onAddRow(newObj, colInfos);
}
if (this.allowRemote(_Const2.default.REMOTE_INSERT_ROW)) {
if (this.props.options.afterInsertRow) {
this.props.options.afterInsertRow(newObj);
}
return null;
}
try {
this.store.add(newObj);
} catch (e) {
return e.message;
}
this._handleAfterAddingRow(newObj, false);
}
}, {
key: 'getSizePerPage',
value: function getSizePerPage() {
return this.state.sizePerPage;
}
}, {
key: 'getCurrentPage',
value: function getCurrentPage() {
return this.state.currPage;
}
}, {
key: 'getTableDataIgnorePaging',
value: function getTableDataIgnorePaging() {
return this.store.getCurrentDisplayData();
}
}, {
key: '__getPageByRowKey__REACT_HOT_LOADER__',
value: function __getPageByRowKey__REACT_HOT_LOADER__(rowKey) {
var sizePerPage = this.state.sizePerPage;
var currentData = this.store.getCurrentDisplayData();
var keyField = this.store.getKeyField();
var result = currentData.findIndex(function (x) {
return x[keyField] === rowKey;
});
if (result > -1) {
return parseInt(result / sizePerPage, 10) + 1;
} else {
return result;
}
}
}, {
key: '__handleDropRow__REACT_HOT_LOADER__',
value: function __handleDropRow__REACT_HOT_LOADER__(rowKeys) {
var _this4 = this;
var dropRowKeys = rowKeys ? rowKeys : this.store.getSelectedRowKeys();
// add confirm before the delete action if that option is set.
if (dropRowKeys && dropRowKeys.length > 0) {
if (this.props.options.handleConfirmDeleteRow) {
this.props.options.handleConfirmDeleteRow(function () {
_this4.deleteRow(dropRowKeys);
}, dropRowKeys);
} else if (confirm('Are you sure you want to delete?')) {
this.deleteRow(dropRowKeys);
}
}
}
}, {
key: 'deleteRow',
value: function deleteRow(dropRowKeys) {
var onDeleteRow = this.props.options.onDeleteRow;
if (onDeleteRow) {
onDeleteRow(dropRowKeys);
}
this.store.setSelectedRowKey([]); // clear selected row key
if (this.allowRemote(_Const2.default.REMOTE_DROP_ROW)) {
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
return;
}
this.store.remove(dropRowKeys); // remove selected Row
var result = void 0;
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
var currPage = this.state.currPage;
if (currPage > currLastPage) currPage = currLastPage;
result = this.store.page(currPage, sizePerPage).get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys(),
currPage: currPage,
reset: false
});
} else {
result = this.store.get();
this.setState({
data: result,
reset: false,
selectedRowKeys: this.store.getSelectedRowKeys()
});
}
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
}
}, {
key: '__handleFilterData__REACT_HOT_LOADER__',
value: function __handleFilterData__REACT_HOT_LOADER__(filterObj) {
var onFilterChange = this.props.options.onFilterChange;
if (onFilterChange) {
var colInfos = this.store.getColInfos();
onFilterChange(filterObj, colInfos);
}
this.setState({
currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX,
reset: false
});
if (this.allowRemote(_Const2.default.REMOTE_FILTER)) {
if (this.props.options.afterColumnFilter) {
this.props.options.afterColumnFilter(filterObj, this.store.getDataIgnoringPagination());
}
return;
}
this.store.filter(filterObj);
var sortList = this.store.getSortInfo();
if (sortList.length > 0) {
this.store.sort();
}
var result = void 0;
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
result = this.store.page(1, sizePerPage).get();
} else {
result = this.store.get();
}
if (this.props.options.afterColumnFilter) {
this.props.options.afterColumnFilter(filterObj, this.store.getDataIgnoringPagination());
}
this.setState({
data: result,
reset: false
});
}
}, {
key: '__handleExportCSV__REACT_HOT_LOADER__',
value: function __handleExportCSV__REACT_HOT_LOADER__() {
var result = {};
var csvFileName = this.props.csvFileName;
var onExportToCSV = this.props.options.onExportToCSV;
if (onExportToCSV) {
result = onExportToCSV();
} else {
result = this.store.getDataIgnoringPagination();
}
var keys = [];
this.props.children.map(function (column) {
if (column.props.export === true || typeof column.props.export === 'undefined' && column.props.hidden === false) {
keys.push({
field: column.props.dataField,
format: column.props.csvFormat,
extraData: column.props.csvFormatExtraData,
header: column.props.csvHeader || column.props.dataField,
row: Number(column.props.row) || 0,
rowSpan: Number(column.props.rowSpan) || 1,
colSpan: Number(column.props.colSpan) || 1
});
}
});
if (typeof csvFileName === 'function') {
csvFileName = csvFileName();
}
(0, _csv_export_util2.default)(result, keys, csvFileName);
}
}, {
key: '__handleSearch__REACT_HOT_LOADER__',
value: function __handleSearch__REACT_HOT_LOADER__(searchText) {
// Set search field if this function being called outside
// but it's not necessary if calling fron inside.
if (this.refs.toolbar) {
this.refs.toolbar.setSearchInput(searchText);
}
var onSearchChange = this.props.options.onSearchChange;
if (onSearchChange) {
var colInfos = this.store.getColInfos();
onSearchChange(searchText, colInfos, this.props.multiColumnSearch);
}
this.setState({
currPage: this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX,
reset: false
});
if (this.allowRemote(_Const2.default.REMOTE_SEARCH)) {
if (this.props.options.afterSearch) {
this.props.options.afterSearch(searchText, this.store.getDataIgnoringPagination());
}
return;
}
this.store.search(searchText);
var sortList = this.store.getSortInfo();
if (sortList.length > 0) {
this.store.sort();
}
var result = void 0;
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
result = this.store.page(1, sizePerPage).get();
} else {
result = this.store.get();
}
if (this.props.options.afterSearch) {
this.props.options.afterSearch(searchText, this.store.getDataIgnoringPagination());
}
this.setState({
data: result,
reset: false
});
}
}, {
key: 'renderPagination',
value: function renderPagination() {
if (this.props.pagination) {
var dataSize = void 0;
if (this.allowRemote(_Const2.default.REMOTE_PAGE)) {
dataSize = this.props.fetchInfo.dataTotalSize;
} else {
dataSize = this.store.getDataNum();
}
var options = this.props.options;
var withFirstAndLast = options.withFirstAndLast === undefined ? true : options.withFirstAndLast;
if (Math.ceil(dataSize / this.state.sizePerPage) <= 1 && this.props.ignoreSinglePage) return null;
return _react2.default.createElement(
'div',
{ className: 'react-bs-table-pagination' },
_react2.default.createElement(_PaginationList2.default, {
ref: 'pagination',
withFirstAndLast: withFirstAndLast,
alwaysShowAllBtns: options.alwaysShowAllBtns,
currPage: this.state.currPage,
changePage: this.handlePaginationData,
sizePerPage: this.state.sizePerPage,
sizePerPageList: options.sizePerPageList || _Const2.default.SIZE_PER_PAGE_LIST,
pageStartIndex: options.pageStartIndex,
paginationShowsTotal: options.paginationShowsTotal,
paginationSize: options.paginationSize || _Const2.default.PAGINATION_SIZE,
dataSize: dataSize,
onSizePerPageList: options.onSizePerPageList,
prePage: options.prePage || _Const2.default.PRE_PAGE,
nextPage: options.nextPage || _Const2.default.NEXT_PAGE,
firstPage: options.firstPage || _Const2.default.FIRST_PAGE,
lastPage: options.lastPage || _Const2.default.LAST_PAGE,
prePageTitle: options.prePageTitle || _Const2.default.PRE_PAGE_TITLE,
nextPageTitle: options.nextPageTitle || _Const2.default.NEXT_PAGE_TITLE,
firstPageTitle: options.firstPageTitle || _Const2.default.FIRST_PAGE_TITLE,
lastPageTitle: options.lastPageTitle || _Const2.default.LAST_PAGE_TITLE,
hideSizePerPage: options.hideSizePerPage,
sizePerPageDropDown: options.sizePerPageDropDown,
hidePageListOnlyOnePage: options.hidePageListOnlyOnePage,
paginationPanel: options.paginationPanel,
open: false })
);
}
return null;
}
}, {
key: 'renderToolBar',
value: function renderToolBar() {
var _props3 = this.props,
exportCSV = _props3.exportCSV,
selectRow = _props3.selectRow,
insertRow = _props3.insertRow,
deleteRow = _props3.deleteRow,
search = _props3.search,
children = _props3.children;
var enableShowOnlySelected = selectRow && selectRow.showOnlySelected;
var print = typeof this.props.options.printToolBar === 'undefined' ? true : this.props.options.printToolBar;
if (enableShowOnlySelected || insertRow || deleteRow || search || exportCSV || this.props.options.searchPanel || this.props.options.btnGroup || this.props.options.toolBar) {
var columns = void 0;
if (Array.isArray(children)) {
columns = children.map(function (column, r) {
var props = column.props;
return {
name: props.headerText || props.children,
field: props.dataField,
hiddenOnInsert: props.hiddenOnInsert,
// when you want same auto generate value and not allow edit, example ID field
autoValue: props.autoValue || false,
// for create editor, no params for column.editable() indicate that editor for new row
editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable,
format: props.dataFormat ? function (value) {
return props.dataFormat(value, null, props.formatExtraData, r).replace(/<.*?>/g, '');
} : false
};
});
} else {
columns = [{
name: children.props.headerText || children.props.children,
field: children.props.dataField,
editable: children.props.editable,
hiddenOnInsert: children.props.hiddenOnInsert
}];
}
return _react2.default.createElement(
'div',
{ className: 'react-bs-table-tool-bar ' + (print ? '' : 'hidden-print') },
_react2.default.createElement(_ToolBar2.default, {
ref: 'toolbar',
defaultSearch: this.props.options.defaultSearch,
clearSearch: this.props.options.clearSearch,
searchPosition: this.props.options.searchPosition,
searchDelayTime: this.props.options.searchDelayTime,
enableInsert: insertRow,
enableDelete: deleteRow,
enableSearch: search,
enableExportCSV: exportCSV,
enableShowOnlySelected: enableShowOnlySelected,
columns: columns,
searchPlaceholder: this.props.searchPlaceholder,
exportCSVText: this.props.options.exportCSVText,
insertText: this.props.options.insertText,
deleteText: this.props.options.deleteText,
saveText: this.props.options.saveText,
closeText: this.props.options.closeText,
ignoreEditable: this.props.options.ignoreEditable,
onAddRow: this.handleAddRow,
onDropRow: this.handleDropRow,
onSearch: this.handleSearch,
onExportCSV: this.handleExportCSV,
onShowOnlySelected: this.handleShowOnlySelected,
insertModalHeader: this.props.options.insertModalHeader,
insertModalFooter: this.props.options.insertModalFooter,
insertModalBody: this.props.options.insertModalBody,
insertModal: this.props.options.insertModal,
insertBtn: this.props.options.insertBtn,
deleteBtn: this.props.options.deleteBtn,
showSelectedOnlyBtn: this.props.options.showSelectedOnlyBtn,
exportCSVBtn: this.props.options.exportCSVBtn,
clearSearchBtn: this.props.options.clearSearchBtn,
searchField: this.props.options.searchField,
searchPanel: this.props.options.searchPanel,
btnGroup: this.props.options.btnGroup,
toolBar: this.props.options.toolBar,
reset: this.state.reset })
);
} else {
return null;
}
}
}, {
key: 'renderTableFilter',
value: function renderTableFilter(columns) {
if (this.props.columnFilter) {
return _react2.default.createElement(_TableFilter2.default, { columns: columns,
rowSelectType: this.props.selectRow.mode,
onFilter: this.handleFilterData });
} else {
return null;
}
}
}, {
key: '___scrollTop__REACT_HOT_LOADER__',
value: function ___scrollTop__REACT_HOT_LOADER__() {
var scrollTop = this.props.scrollTop;
if (scrollTop === _Const2.default.SCROLL_TOP) {
this.refs.body.refs.container.scrollTop = 0;
} else if (scrollTop === _Const2.default.SCROLL_BOTTOM) {
this.refs.body.refs.container.scrollTop = this.refs.body.refs.container.scrollHeight;
} else if (typeof scrollTop === 'number' && !isNaN(scrollTop)) {
this.refs.body.refs.container.scrollTop = scrollTop;
}
}
}, {
key: '___scrollHeader__REACT_HOT_LOADER__',
value: function ___scrollHeader__REACT_HOT_LOADER__(e) {
this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft;
}
}, {
key: '_adjustTable',
value: function _adjustTable() {
this._adjustHeight();
if (!this.props.printable) {
this._adjustHeaderWidth();
}
}
}, {
key: '_adjustHeaderWidth',
value: function _adjustHeaderWidth() {
var header = this.refs.header.getHeaderColGrouop();
var tbody = this.refs.body.refs.tbody;
var bodyHeader = this.refs.body.getHeaderColGrouop();
var firstRow = tbody.childNodes[0];
var isScroll = tbody.parentNode.getBoundingClientRect().height > tbody.parentNode.parentNode.getBoundingClientRect().height;
var scrollBarWidth = isScroll ? _util2.default.getScrollBarWidth() : 0;
if (firstRow && this.store.getDataNum()) {
if (isScroll) {
var cells = firstRow.childNodes;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var computedStyle = window.getComputedStyle(cell);
var width = parseFloat(computedStyle.width.replace('px', ''));
if (this.isIE) {
var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', ''));
var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', ''));
var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', ''));
var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', ''));
width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth;
}
var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0;
if (width <= 0) {
width = 120;
cell.width = width + lastPadding + 'px';
}
var result = width + lastPadding + 'px';
header[i].style.width = result;
header[i].style.minWidth = result;
if (cells.length - 1 === i) {
bodyHeader[i].style.width = width + 'px';
bodyHeader[i].style.minWidth = width + 'px';
} else {
bodyHeader[i].style.width = result;
bodyHeader[i].style.minWidth = result;
}
}
}
} else {
_react2.default.Children.forEach(this.props.children, function (child, i) {
if (child.props.width) {
header[i].style.width = child.props.width + 'px';
header[i].style.minWidth = child.props.width + 'px';
}
});
}
}
}, {
key: '_adjustHeight',
value: function _adjustHeight() {
var height = this.props.height;
var maxHeight = this.props.maxHeight;
if (typeof height === 'number' && !isNaN(height) || height.indexOf('%') === -1) {
this.refs.body.refs.container.style.height = parseFloat(height, 10) - this.refs.header.refs.container.offsetHeight + 'px';
}
if (maxHeight) {
maxHeight = typeof maxHeight === 'number' ? maxHeight : parseInt(maxHeight.replace('px', ''), 10);
this.refs.body.refs.container.style.maxHeight = maxHeight - this.refs.header.refs.container.offsetHeight + 'px';
}
}
}, {
key: '_handleAfterAddingRow',
value: function _handleAfterAddingRow(newObj, atTheBeginning) {
var result = void 0;
if (this.props.pagination) {
// if pagination is enabled and inserting row at the end,
// change page to the last page
// otherwise, change it to the first page
var sizePerPage = this.state.sizePerPage;
if (atTheBeginning) {
var firstPage = this.props.options.pageStartIndex || _Const2.default.PAGE_START_INDEX;
result = this.store.page(firstPage, sizePerPage).get();
this.setState({
data: result,
currPage: firstPage,
reset: false
});
} else {
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
result = this.store.page(currLastPage, sizePerPage).get();
this.setState({
data: result,
currPage: currLastPage,
reset: false
});
}
} else {
result = this.store.get();
this.setState({
data: result,
reset: false
});
}
if (this.props.options.afterInsertRow) {
this.props.options.afterInsertRow(newObj);
}
}
}]);
return BootstrapTable;
}(_react.Component);
BootstrapTable.propTypes = {
keyField: _react.PropTypes.string,
height: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
maxHeight: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]),
remote: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), // remote data, default is false
scrollTop: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
pagination: _react.PropTypes.bool,
printable: _react.PropTypes.bool,
keyBoardNav: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
searchPlaceholder: _react.PropTypes.string,
selectRow: _react.PropTypes.shape({
mode: _react.PropTypes.oneOf([_Const2.default.ROW_SELECT_NONE, _Const2.default.ROW_SELECT_SINGLE, _Const2.default.ROW_SELECT_MULTI]),
customComponent: _react.PropTypes.func,
bgColor: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]),
selected: _react.PropTypes.array,
onSelect: _react.PropTypes.func,
onSelectAll: _react.PropTypes.func,
clickToSelect: _react.PropTypes.bool,
hideSelectColumn: _react.PropTypes.bool,
clickToSelectAndEditCell: _react.PropTypes.bool,
clickToExpand: _react.PropTypes.bool,
showOnlySelected: _react.PropTypes.bool,
unselectable: _react.PropTypes.array,
columnWidth: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string])
}),
cellEdit: _react.PropTypes.shape({
mode: _react.PropTypes.string,
blurToSave: _react.PropTypes.bool,
beforeSaveCell: _react.PropTypes.func,
afterSaveCell: _react.PropTypes.func,
nonEditableRows: _react.PropTypes.func
}),
insertRow: _react.PropTypes.bool,
deleteRow: _react.PropTypes.bool,
search: _react.PropTypes.bool,
columnFilter: _react.PropTypes.bool,
trClassName: _react.PropTypes.any,
tableStyle: _react.PropTypes.object,
containerStyle: _react.PropTypes.object,
headerStyle: _react.PropTypes.object,
bodyStyle: _react.PropTypes.object,
containerClass: _react.PropTypes.string,
tableContainerClass: _react.PropTypes.string,
headerContainerClass: _react.PropTypes.string,
bodyContainerClass: _react.PropTypes.string,
tableHeaderClass: _react.PropTypes.string,
tableBodyClass: _react.PropTypes.string,
options: _react.PropTypes.shape({
clearSearch: _react.PropTypes.bool,
sortName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]),
sortOrder: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]),
defaultSortName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]),
defaultSortOrder: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.array]),
sortIndicator: _react.PropTypes.bool,
afterTableComplete: _react.PropTypes.func,
afterDeleteRow: _react.PropTypes.func,
afterInsertRow: _react.PropTypes.func,
afterSearch: _react.PropTypes.func,
afterColumnFilter: _react.PropTypes.func,
onRowClick: _react.PropTypes.func,
onRowDoubleClick: _react.PropTypes.func,
page: _react.PropTypes.number,
pageStartIndex: _react.PropTypes.number,
paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
sizePerPageList: _react.PropTypes.array,
sizePerPage: _react.PropTypes.number,
paginationSize: _react.PropTypes.number,
paginationPosition: _react.PropTypes.oneOf([_Const2.default.PAGINATION_POS_TOP, _Const2.default.PAGINATION_POS_BOTTOM, _Const2.default.PAGINATION_POS_BOTH]),
hideSizePerPage: _react.PropTypes.bool,
hidePageListOnlyOnePage: _react.PropTypes.bool,
alwaysShowAllBtns: _react.PropTypes.bool,
withFirstAndLast: _react.PropTypes.bool,
onSortChange: _react.PropTypes.func,
onPageChange: _react.PropTypes.func,
onSizePerPageList: _react.PropTypes.func,
onFilterChange: _react2.default.PropTypes.func,
onSearchChange: _react2.default.PropTypes.func,
onAddRow: _react2.default.PropTypes.func,
onExportToCSV: _react2.default.PropTypes.func,
onCellEdit: _react2.default.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
withoutNoDataText: _react2.default.PropTypes.bool,
handleConfirmDeleteRow: _react.PropTypes.func,
prePage: _react.PropTypes.string,
nextPage: _react.PropTypes.string,
firstPage: _react.PropTypes.string,
lastPage: _react.PropTypes.string,
prePageTitle: _react.PropTypes.string,
nextPageTitle: _react.PropTypes.string,
firstPageTitle: _react.PropTypes.string,
lastPageTitle: _react.PropTypes.string,
searchDelayTime: _react.PropTypes.number,
exportCSVText: _react.PropTypes.string,
insertText: _react.PropTypes.string,
deleteText: _react.PropTypes.string,
saveText: _react.PropTypes.string,
closeText: _react.PropTypes.string,
ignoreEditable: _react.PropTypes.bool,
defaultSearch: _react.PropTypes.string,
insertModalHeader: _react.PropTypes.func,
insertModalBody: _react.PropTypes.func,
insertModalFooter: _react.PropTypes.func,
insertModal: _react.PropTypes.func,
insertBtn: _react.PropTypes.func,
deleteBtn: _react.PropTypes.func,
showSelectedOnlyBtn: _react.PropTypes.func,
exportCSVBtn: _react.PropTypes.func,
clearSearchBtn: _react.PropTypes.func,
searchField: _react.PropTypes.func,
searchPanel: _react.PropTypes.func,
btnGroup: _react.PropTypes.func,
toolBar: _react.PropTypes.func,
sizePerPageDropDown: _react.PropTypes.func,
paginationPanel: _react.PropTypes.func,
searchPosition: _react.PropTypes.string,
expandRowBgColor: _react.PropTypes.string,
expandBy: _react.PropTypes.string,
expanding: _react.PropTypes.array,
beforeShowError: _react.PropTypes.func,
printToolBar: _react.PropTypes.bool
}),
fetchInfo: _react.PropTypes.shape({
dataTotalSize: _react.PropTypes.number
}),
exportCSV: _react.PropTypes.bool,
csvFileName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]),
ignoreSinglePage: _react.PropTypes.bool,
expandableRow: _react.PropTypes.func,
expandComponent: _react.PropTypes.func,
expandColumnOptions: _react.PropTypes.shape({
columnWidth: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
expandColumnVisible: _react.PropTypes.bool,
expandColumnComponent: _react.PropTypes.func,
expandColumnBeforeSelectColumn: _react.PropTypes.bool
})
};
BootstrapTable.defaultProps = {
scrollTop: undefined,
expandComponent: undefined,
expandableRow: undefined,
expandColumnOptions: {
expandColumnVisible: false,
expandColumnComponent: undefined,
expandColumnBeforeSelectColumn: true
},
height: '100%',
maxHeight: undefined,
striped: false,
bordered: true,
hover: false,
condensed: false,
pagination: false,
printable: false,
keyBoardNav: false,
searchPlaceholder: undefined,
selectRow: {
mode: _Const2.default.ROW_SELECT_NONE,
bgColor: _Const2.default.ROW_SELECT_BG_COLOR,
selected: [],
onSelect: undefined,
onSelectAll: undefined,
clickToSelect: false,
hideSelectColumn: false,
clickToSelectAndEditCell: false,
clickToExpand: false,
showOnlySelected: false,
unselectable: [],
customComponent: undefined
},
cellEdit: {
mode: _Const2.default.CELL_EDIT_NONE,
blurToSave: false,
beforeSaveCell: undefined,
afterSaveCell: undefined,
nonEditableRows: undefined
},
insertRow: false,
deleteRow: false,
search: false,
multiColumnSearch: false,
multiColumnSort: 1,
columnFilter: false,
trClassName: '',
tableStyle: undefined,
containerStyle: undefined,
headerStyle: undefined,
bodyStyle: undefined,
containerClass: null,
tableContainerClass: null,
headerContainerClass: null,
bodyContainerClass: null,
tableHeaderClass: null,
tableBodyClass: null,
options: {
clearSearch: false,
sortName: undefined,
sortOrder: undefined,
defaultSortName: undefined,
defaultSortOrder: undefined,
sortIndicator: true,
afterTableComplete: undefined,
afterDeleteRow: undefined,
afterInsertRow: undefined,
afterSearch: undefined,
afterColumnFilter: undefined,
onRowClick: undefined,
onRowDoubleClick: undefined,
onMouseLeave: undefined,
onMouseEnter: undefined,
onRowMouseOut: undefined,
onRowMouseOver: undefined,
page: undefined,
paginationShowsTotal: false,
sizePerPageList: _Const2.default.SIZE_PER_PAGE_LIST,
sizePerPage: undefined,
paginationSize: _Const2.default.PAGINATION_SIZE,
paginationPosition: _Const2.default.PAGINATION_POS_BOTTOM,
hideSizePerPage: false,
hidePageListOnlyOnePage: false,
alwaysShowAllBtns: false,
withFirstAndLast: true,
onSizePerPageList: undefined,
noDataText: undefined,
withoutNoDataText: false,
handleConfirmDeleteRow: undefined,
prePage: _Const2.default.PRE_PAGE,
nextPage: _Const2.default.NEXT_PAGE,
firstPage: _Const2.default.FIRST_PAGE,
lastPage: _Const2.default.LAST_PAGE,
prePageTitle: _Const2.default.PRE_PAGE_TITLE,
nextPageTitle: _Const2.default.NEXT_PAGE_TITLE,
firstPageTitle: _Const2.default.FIRST_PAGE_TITLE,
lastPageTitle: _Const2.default.LAST_PAGE_TITLE,
pageStartIndex: undefined,
searchDelayTime: undefined,
exportCSVText: _Const2.default.EXPORT_CSV_TEXT,
insertText: _Const2.default.INSERT_BTN_TEXT,
deleteText: _Const2.default.DELETE_BTN_TEXT,
saveText: _Const2.default.SAVE_BTN_TEXT,
closeText: _Const2.default.CLOSE_BTN_TEXT,
ignoreEditable: false,
defaultSearch: '',
insertModalHeader: undefined,
insertModalBody: undefined,
insertModalFooter: undefined,
insertModal: undefined,
insertBtn: undefined,
deleteBtn: undefined,
showSelectedOnlyBtn: undefined,
exportCSVBtn: undefined,
clearSearchBtn: undefined,
searchField: undefined,
searchPanel: undefined,
btnGroup: undefined,
toolBar: undefined,
sizePerPageDropDown: undefined,
paginationPanel: undefined,
searchPosition: 'right',
expandRowBgColor: undefined,
expandBy: _Const2.default.EXPAND_BY_ROW,
expanding: [],
beforeShowError: undefined,
printToolBar: true
},
fetchInfo: {
dataTotalSize: 0
},
exportCSV: false,
csvFileName: 'spreadsheet.csv',
ignoreSinglePage: false
};
var _default = BootstrapTable;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(BootstrapTable, 'BootstrapTable', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/BootstrapTable.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/BootstrapTable.js');
}();
;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var CONST_VAR = {
SORT_DESC: 'desc',
SORT_ASC: 'asc',
SIZE_PER_PAGE: 10,
NEXT_PAGE: '>',
NEXT_PAGE_TITLE: 'next page',
LAST_PAGE: '>>',
LAST_PAGE_TITLE: 'last page',
PRE_PAGE: '<',
PRE_PAGE_TITLE: 'previous page',
FIRST_PAGE: '<<',
FIRST_PAGE_TITLE: 'first page',
PAGE_START_INDEX: 1,
ROW_SELECT_BG_COLOR: '',
ROW_SELECT_NONE: 'none',
ROW_SELECT_SINGLE: 'radio',
ROW_SELECT_MULTI: 'checkbox',
CELL_EDIT_NONE: 'none',
CELL_EDIT_CLICK: 'click',
CELL_EDIT_DBCLICK: 'dbclick',
SIZE_PER_PAGE_LIST: [10, 25, 30, 50],
PAGINATION_SIZE: 5,
PAGINATION_POS_TOP: 'top',
PAGINATION_POS_BOTTOM: 'bottom',
PAGINATION_POS_BOTH: 'both',
NO_DATA_TEXT: 'There is no data to display',
SHOW_ONLY_SELECT: 'Show Selected Only',
SHOW_ALL: 'Show All',
EXPORT_CSV_TEXT: 'Export to CSV',
INSERT_BTN_TEXT: 'New',
DELETE_BTN_TEXT: 'Delete',
SAVE_BTN_TEXT: 'Save',
CLOSE_BTN_TEXT: 'Close',
FILTER_DELAY: 500,
SCROLL_TOP: 'Top',
SCROLL_BOTTOM: 'Bottom',
FILTER_TYPE: {
TEXT: 'TextFilter',
REGEX: 'RegexFilter',
SELECT: 'SelectFilter',
NUMBER: 'NumberFilter',
DATE: 'DateFilter',
CUSTOM: 'CustomFilter'
},
FILTER_COND_EQ: 'eq',
FILTER_COND_LIKE: 'like',
EXPAND_BY_ROW: 'row',
EXPAND_BY_COL: 'column',
CANCEL_TOASTR: 'Pressed ESC can cancel',
REMOTE_SORT: 'sort',
REMOTE_PAGE: 'pagination',
REMOTE_CELL_EDIT: 'cellEdit',
REMOTE_INSERT_ROW: 'insertRow',
REMOTE_DROP_ROW: 'dropRow',
REMOTE_FILTER: 'filter',
REMOTE_SEARCH: 'search',
REMOTE_EXPORT_CSV: 'exportCSV'
};
CONST_VAR.REMOTE = {};
CONST_VAR.REMOTE[CONST_VAR.REMOTE_SORT] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_PAGE] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_CELL_EDIT] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_INSERT_ROW] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_DROP_ROW] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_FILTER] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_SEARCH] = false;
CONST_VAR.REMOTE[CONST_VAR.REMOTE_EXPORT_CSV] = false;
var _default = CONST_VAR;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(CONST_VAR, 'CONST_VAR', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Const.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Const.js');
}();
;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _SelectRowHeaderColumn = __webpack_require__(7);
var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Checkbox = function (_Component) {
_inherits(Checkbox, _Component);
function Checkbox() {
_classCallCheck(this, Checkbox);
return _possibleConstructorReturn(this, (Checkbox.__proto__ || Object.getPrototypeOf(Checkbox)).apply(this, arguments));
}
_createClass(Checkbox, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.update(this.props.checked);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.update(props.checked);
}
}, {
key: 'update',
value: function update(checked) {
_reactDom2.default.findDOMNode(this).indeterminate = checked === 'indeterminate';
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement('input', { className: 'react-bs-select-all',
type: 'checkbox',
checked: this.props.checked,
onChange: this.props.onChange });
}
}]);
return Checkbox;
}(_react.Component);
function getSortOrder(sortList, field, enableSort) {
if (!enableSort) return undefined;
var result = sortList.filter(function (sortObj) {
return sortObj.sortField === field;
});
if (result.length > 0) {
return result[0].order;
} else {
return undefined;
}
}
var TableHeader = function (_Component2) {
_inherits(TableHeader, _Component2);
function TableHeader() {
var _ref;
var _temp, _this2, _ret;
_classCallCheck(this, TableHeader);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this2 = _possibleConstructorReturn(this, (_ref = TableHeader.__proto__ || Object.getPrototypeOf(TableHeader)).call.apply(_ref, [this].concat(args))), _this2), _this2.getHeaderColGrouop = function () {
var _this3;
return (_this3 = _this2).__getHeaderColGrouop__REACT_HOT_LOADER__.apply(_this3, arguments);
}, _temp), _possibleConstructorReturn(_this2, _ret);
}
_createClass(TableHeader, [{
key: 'render',
value: function render() {
var containerClasses = (0, _classnames2.default)('react-bs-container-header', 'table-header-wrapper', this.props.headerContainerClass);
var tableClasses = (0, _classnames2.default)('table', 'table-hover', {
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed
}, this.props.tableHeaderClass);
var rowCount = Math.max.apply(Math, _toConsumableArray(_react2.default.Children.map(this.props.children, function (elm) {
return elm.props.row ? Number(elm.props.row) : 0;
})));
var rows = [];
var rowKey = 0;
rows[0] = [];
rows[0].push([this.props.expandColumnVisible && this.props.expandColumnBeforeSelectColumn && _react2.default.createElement(
'th',
{ className: 'react-bs-table-expand-cell' },
' '
)], [this.renderSelectRowHeader(rowCount + 1, rowKey++)], [this.props.expandColumnVisible && !this.props.expandColumnBeforeSelectColumn && _react2.default.createElement(
'th',
{ className: 'react-bs-table-expand-cell' },
' '
)]);
var _props = this.props,
sortIndicator = _props.sortIndicator,
sortList = _props.sortList,
onSort = _props.onSort,
reset = _props.reset;
_react2.default.Children.forEach(this.props.children, function (elm) {
var _elm$props = elm.props,
dataField = _elm$props.dataField,
dataSort = _elm$props.dataSort;
var sort = getSortOrder(sortList, dataField, dataSort);
var rowIndex = elm.props.row ? Number(elm.props.row) : 0;
var rowSpan = elm.props.rowSpan ? Number(elm.props.rowSpan) : 1;
if (rows[rowIndex] === undefined) {
rows[rowIndex] = [];
}
if (rowSpan + rowIndex === rowCount + 1) {
rows[rowIndex].push(_react2.default.cloneElement(elm, { reset: reset, key: rowKey++, onSort: onSort, sort: sort, sortIndicator: sortIndicator, isOnlyHead: false }));
} else {
rows[rowIndex].push(_react2.default.cloneElement(elm, { key: rowKey++, isOnlyHead: true }));
}
});
var trs = rows.map(function (row, indexRow) {
return _react2.default.createElement(
'tr',
{ key: indexRow },
row
);
});
return _react2.default.createElement(
'div',
{ ref: 'container', className: containerClasses, style: this.props.style },
_react2.default.createElement(
'table',
{ className: tableClasses },
_react2.default.cloneElement(this.props.colGroups, { ref: 'headerGrp' }),
_react2.default.createElement(
'thead',
{ ref: 'header' },
trs
)
)
);
}
}, {
key: '__getHeaderColGrouop__REACT_HOT_LOADER__',
value: function __getHeaderColGrouop__REACT_HOT_LOADER__() {
return this.refs.headerGrp.childNodes;
}
}, {
key: 'renderSelectRowHeader',
value: function renderSelectRowHeader(rowCount, rowKey) {
if (this.props.hideSelectColumn) {
return null;
} else if (this.props.customComponent) {
var CustomComponent = this.props.customComponent;
return _react2.default.createElement(
_SelectRowHeaderColumn2.default,
{ key: rowKey, rowCount: rowCount },
_react2.default.createElement(CustomComponent, { type: 'checkbox', checked: this.props.isSelectAll,
indeterminate: this.props.isSelectAll === 'indeterminate', disabled: false,
onChange: this.props.onSelectAllRow, rowIndex: 'Header' })
);
} else if (this.props.rowSelectType === _Const2.default.ROW_SELECT_SINGLE) {
return _react2.default.createElement(_SelectRowHeaderColumn2.default, { key: rowKey, rowCount: rowCount });
} else if (this.props.rowSelectType === _Const2.default.ROW_SELECT_MULTI) {
return _react2.default.createElement(
_SelectRowHeaderColumn2.default,
{ key: rowKey, rowCount: rowCount },
_react2.default.createElement(Checkbox, {
onChange: this.props.onSelectAllRow,
checked: this.props.isSelectAll })
);
} else {
return null;
}
}
}]);
return TableHeader;
}(_react.Component);
TableHeader.propTypes = {
headerContainerClass: _react.PropTypes.string,
tableHeaderClass: _react.PropTypes.string,
style: _react.PropTypes.object,
rowSelectType: _react.PropTypes.string,
onSort: _react.PropTypes.func,
onSelectAllRow: _react.PropTypes.func,
sortList: _react.PropTypes.array,
hideSelectColumn: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
isFiltered: _react.PropTypes.bool,
isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]),
sortIndicator: _react.PropTypes.bool,
customComponent: _react.PropTypes.func,
colGroups: _react.PropTypes.element,
reset: _react.PropTypes.bool,
expandColumnVisible: _react.PropTypes.bool,
expandColumnComponent: _react.PropTypes.func,
expandColumnBeforeSelectColumn: _react.PropTypes.bool
};
var _default = TableHeader;
exports.default = _default;
;
var _temp2 = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(Checkbox, 'Checkbox', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js');
__REACT_HOT_LOADER__.register(getSortOrder, 'getSortOrder', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js');
__REACT_HOT_LOADER__.register(TableHeader, 'TableHeader', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeader.js');
}();
;
/***/ },
/* 6 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_6__;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SelectRowHeaderColumn = function (_Component) {
_inherits(SelectRowHeaderColumn, _Component);
function SelectRowHeaderColumn() {
_classCallCheck(this, SelectRowHeaderColumn);
return _possibleConstructorReturn(this, (SelectRowHeaderColumn.__proto__ || Object.getPrototypeOf(SelectRowHeaderColumn)).apply(this, arguments));
}
_createClass(SelectRowHeaderColumn, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'th',
{ rowSpan: this.props.rowCount, style: { textAlign: 'center' },
'data-is-only-head': false },
this.props.children
);
}
}]);
return SelectRowHeaderColumn;
}(_react.Component);
SelectRowHeaderColumn.propTypes = {
children: _react.PropTypes.node,
rowCount: _react.PropTypes.number
};
var _default = SelectRowHeaderColumn;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(SelectRowHeaderColumn, 'SelectRowHeaderColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/SelectRowHeaderColumn.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/SelectRowHeaderColumn.js');
}();
;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _TableRow = __webpack_require__(10);
var _TableRow2 = _interopRequireDefault(_TableRow);
var _TableColumn = __webpack_require__(11);
var _TableColumn2 = _interopRequireDefault(_TableColumn);
var _TableEditColumn = __webpack_require__(12);
var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _ExpandComponent = __webpack_require__(179);
var _ExpandComponent2 = _interopRequireDefault(_ExpandComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var isFun = function isFun(obj) {
return obj && typeof obj === 'function';
};
var TableBody = function (_Component) {
_inherits(TableBody, _Component);
function TableBody(props) {
_classCallCheck(this, TableBody);
var _this = _possibleConstructorReturn(this, (TableBody.__proto__ || Object.getPrototypeOf(TableBody)).call(this, props));
_this.handleCellKeyDown = function () {
return _this.__handleCellKeyDown__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowMouseOut = function () {
return _this.__handleRowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowMouseOver = function () {
return _this.__handleRowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowClick = function () {
return _this.__handleRowClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleRowDoubleClick = function () {
return _this.__handleRowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleSelectRow = function () {
return _this.__handleSelectRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleSelectRowColumChange = function () {
return _this.__handleSelectRowColumChange__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleClickCell = function () {
return _this.__handleClickCell__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleEditCell = function () {
return _this.__handleEditCell__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.nextEditableCell = function () {
return _this.__nextEditableCell__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleCompleteEditCell = function () {
return _this.__handleCompleteEditCell__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleClickonSelectColumn = function () {
return _this.__handleClickonSelectColumn__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.getHeaderColGrouop = function () {
return _this.__getHeaderColGrouop__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.state = {
currEditCell: null
};
return _this;
}
_createClass(TableBody, [{
key: 'render',
value: function render() {
var _props = this.props,
cellEdit = _props.cellEdit,
beforeShowError = _props.beforeShowError,
x = _props.x,
y = _props.y,
keyBoardNav = _props.keyBoardNav;
var tableClasses = (0, _classnames2.default)('table', {
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-hover': this.props.hover,
'table-condensed': this.props.condensed
}, this.props.tableBodyClass);
var noneditableRows = cellEdit.nonEditableRows && cellEdit.nonEditableRows() || [];
var unselectable = this.props.selectRow.unselectable || [];
var isSelectRowDefined = this._isSelectRowDefined();
var tableHeader = _util2.default.renderColGroup(this.props.columns, this.props.selectRow, this.props.expandColumnOptions);
var inputType = this.props.selectRow.mode === _Const2.default.ROW_SELECT_SINGLE ? 'radio' : 'checkbox';
var CustomComponent = this.props.selectRow.customComponent;
var enableKeyBoardNav = keyBoardNav === true || (typeof keyBoardNav === 'undefined' ? 'undefined' : _typeof(keyBoardNav)) === 'object';
var customEditAndNavStyle = (typeof keyBoardNav === 'undefined' ? 'undefined' : _typeof(keyBoardNav)) === 'object' ? keyBoardNav.customStyleOnEditCell : null;
var customNavStyle = (typeof keyBoardNav === 'undefined' ? 'undefined' : _typeof(keyBoardNav)) === 'object' ? keyBoardNav.customStyle : null;
var ExpandColumnCustomComponent = this.props.expandColumnOptions.expandColumnComponent;
var expandColSpan = this.props.columns.filter(function (col) {
return !col.hidden;
}).length;
if (isSelectRowDefined && !this.props.selectRow.hideSelectColumn) {
expandColSpan += 1;
}
var tabIndex = 1;
if (this.props.expandColumnOptions.expandColumnVisible) {
expandColSpan += 1;
}
var tableRows = this.props.data.map(function (data, r) {
var tableColumns = this.props.columns.map(function (column, i) {
var fieldValue = data[column.name];
var isFocusCell = r === y && i === x;
if (column.name !== this.props.keyField && // Key field can't be edit
column.editable && // column is editable? default is true, user can set it false
this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i && noneditableRows.indexOf(data[this.props.keyField]) === -1) {
var editable = column.editable;
var format = column.format ? function (value) {
return column.format(value, data, column.formatExtraData, r).replace(/<.*?>/g, '');
} : false;
if (isFun(column.editable)) {
editable = column.editable(fieldValue, data, r, i);
}
return _react2.default.createElement(_TableEditColumn2.default, {
completeEdit: this.handleCompleteEditCell
// add by bluespring for column editor customize
, editable: editable,
customEditor: column.customEditor,
format: column.format ? format : false,
key: i,
blurToSave: cellEdit.blurToSave,
onTab: this.handleEditCell,
rowIndex: r,
colIndex: i,
row: data,
fieldValue: fieldValue,
className: column.editClassName,
invalidColumnClassName: column.invalidEditColumnClassName,
beforeShowError: beforeShowError,
isFocus: isFocusCell,
customStyleWithNav: customEditAndNavStyle });
} else {
// add by bluespring for className customize
var columnChild = fieldValue && fieldValue.toString();
var columnTitle = null;
var tdClassName = column.className;
if (isFun(column.className)) {
tdClassName = column.className(fieldValue, data, r, i);
}
if (typeof column.format !== 'undefined') {
var formattedValue = column.format(fieldValue, data, column.formatExtraData, r);
if (!_react2.default.isValidElement(formattedValue)) {
columnChild = _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } });
} else {
columnChild = formattedValue;
columnTitle = column.columnTitle && formattedValue ? formattedValue.toString() : null;
}
} else {
columnTitle = column.columnTitle && fieldValue ? fieldValue.toString() : null;
}
return _react2.default.createElement(
_TableColumn2.default,
{ key: i,
rIndex: r,
dataAlign: column.align,
className: tdClassName,
columnTitle: columnTitle,
cellEdit: cellEdit,
hidden: column.hidden,
onEdit: this.handleEditCell,
width: column.width,
onClick: this.handleClickCell,
attrs: column.attrs,
style: column.style,
tabIndex: tabIndex++ + '',
isFocus: isFocusCell,
keyBoardNav: enableKeyBoardNav,
onKeyDown: this.handleCellKeyDown,
customNavStyle: customNavStyle,
row: data },
columnChild
);
}
}, this);
var key = data[this.props.keyField];
var disable = unselectable.indexOf(key) !== -1;
var selected = this.props.selectedRowKeys.indexOf(key) !== -1;
var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected, inputType, disable, CustomComponent, r, data) : null;
var expandedRowColumn = this.renderExpandRowColumn(this.props.expandableRow && this.props.expandableRow(data), this.props.expanding.indexOf(key) > -1, ExpandColumnCustomComponent, r, data);
// add by bluespring for className customize
var trClassName = this.props.trClassName;
if (isFun(this.props.trClassName)) {
trClassName = this.props.trClassName(data, r);
}
var result = [_react2.default.createElement(
_TableRow2.default,
{ isSelected: selected, key: key, className: trClassName,
index: r,
row: data,
selectRow: isSelectRowDefined ? this.props.selectRow : undefined,
enableCellEdit: cellEdit.mode !== _Const2.default.CELL_EDIT_NONE,
onRowClick: this.handleRowClick,
onRowDoubleClick: this.handleRowDoubleClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
onExpandRow: this.handleClickCell,
unselectableRow: disable },
this.props.expandColumnOptions.expandColumnVisible && this.props.expandColumnOptions.expandColumnBeforeSelectColumn && expandedRowColumn,
selectRowColumn,
this.props.expandColumnOptions.expandColumnVisible && !this.props.expandColumnOptions.expandColumnBeforeSelectColumn && expandedRowColumn,
tableColumns
)];
if (this.props.expandableRow && this.props.expandableRow(data)) {
result.push(_react2.default.createElement(
_ExpandComponent2.default,
{
key: key + '-expand',
className: trClassName,
bgColor: this.props.expandRowBgColor || this.props.selectRow.bgColor || undefined,
hidden: !(this.props.expanding.indexOf(key) > -1),
colSpan: expandColSpan,
width: "100%" },
this.props.expandComponent(data)
));
}
return result;
}, this);
if (tableRows.length === 0 && !this.props.withoutNoDataText) {
var colSpan = this.props.columns.filter(function (c) {
return !c.hidden;
}).length + (isSelectRowDefined ? 1 : 0);
tableRows = [_react2.default.createElement(
_TableRow2.default,
{ key: '##table-empty##' },
_react2.default.createElement(
'td',
{ 'data-toggle': 'collapse',
colSpan: colSpan,
className: 'react-bs-table-no-data' },
this.props.noDataText || _Const2.default.NO_DATA_TEXT
)
)];
}
return _react2.default.createElement(
'div',
{ ref: 'container',
className: (0, _classnames2.default)('react-bs-container-body', this.props.bodyContainerClass),
style: this.props.style },
_react2.default.createElement(
'table',
{ className: tableClasses },
_react2.default.cloneElement(tableHeader, { ref: 'header' }),
_react2.default.createElement(
'tbody',
{ ref: 'tbody' },
tableRows
)
)
);
}
}, {
key: '__handleCellKeyDown__REACT_HOT_LOADER__',
value: function __handleCellKeyDown__REACT_HOT_LOADER__(e, lastEditCell) {
e.preventDefault();
var _props2 = this.props,
keyBoardNav = _props2.keyBoardNav,
onNavigateCell = _props2.onNavigateCell,
cellEdit = _props2.cellEdit;
var offset = void 0;
if (e.keyCode === 37) {
offset = { x: -1, y: 0 };
} else if (e.keyCode === 38) {
offset = { x: 0, y: -1 };
} else if (e.keyCode === 39 || e.keyCode === 9) {
offset = { x: 1, y: 0 };
if (e.keyCode === 9 && lastEditCell) {
offset = _extends({}, offset, {
lastEditCell: lastEditCell
});
}
} else if (e.keyCode === 40) {
offset = { x: 0, y: 1 };
} else if (e.keyCode === 13) {
var enterToEdit = (typeof keyBoardNav === 'undefined' ? 'undefined' : _typeof(keyBoardNav)) === 'object' ? keyBoardNav.enterToEdit : false;
if (cellEdit && enterToEdit) {
this.handleEditCell(e.target.parentElement.rowIndex + 1, e.currentTarget.cellIndex, '', e);
}
}
if (offset && keyBoardNav) {
onNavigateCell(offset);
}
}
}, {
key: '__handleRowMouseOut__REACT_HOT_LOADER__',
value: function __handleRowMouseOut__REACT_HOT_LOADER__(rowIndex, event) {
var targetRow = this.props.data[rowIndex];
this.props.onRowMouseOut(targetRow, event);
}
}, {
key: '__handleRowMouseOver__REACT_HOT_LOADER__',
value: function __handleRowMouseOver__REACT_HOT_LOADER__(rowIndex, event) {
var targetRow = this.props.data[rowIndex];
this.props.onRowMouseOver(targetRow, event);
}
}, {
key: '__handleRowClick__REACT_HOT_LOADER__',
value: function __handleRowClick__REACT_HOT_LOADER__(rowIndex, cellIndex) {
var onRowClick = this.props.onRowClick;
if (this._isSelectRowDefined()) cellIndex--;
if (this._isExpandColumnVisible()) cellIndex--;
onRowClick(this.props.data[rowIndex - 1], rowIndex - 1, cellIndex);
}
}, {
key: '__handleRowDoubleClick__REACT_HOT_LOADER__',
value: function __handleRowDoubleClick__REACT_HOT_LOADER__(rowIndex) {
var onRowDoubleClick = this.props.onRowDoubleClick;
var targetRow = this.props.data[rowIndex];
onRowDoubleClick(targetRow);
}
}, {
key: '__handleSelectRow__REACT_HOT_LOADER__',
value: function __handleSelectRow__REACT_HOT_LOADER__(rowIndex, isSelected, e) {
var selectedRow = void 0;
var _props3 = this.props,
data = _props3.data,
onSelectRow = _props3.onSelectRow;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
return false;
}
});
onSelectRow(selectedRow, isSelected, e);
}
}, {
key: '__handleSelectRowColumChange__REACT_HOT_LOADER__',
value: function __handleSelectRowColumChange__REACT_HOT_LOADER__(e, rowIndex) {
if (!this.props.selectRow.clickToSelect || !this.props.selectRow.clickToSelectAndEditCell) {
this.handleSelectRow(rowIndex + 1, e.currentTarget.checked, e);
}
}
}, {
key: '__handleClickCell__REACT_HOT_LOADER__',
value: function __handleClickCell__REACT_HOT_LOADER__(rowIndex) {
var _this2 = this;
var columnIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
var _props4 = this.props,
columns = _props4.columns,
keyField = _props4.keyField,
expandBy = _props4.expandBy,
expandableRow = _props4.expandableRow,
clickToExpand = _props4.selectRow.clickToExpand;
var selectRowAndExpand = this._isSelectRowDefined() && !clickToExpand ? false : true;
columnIndex = this._isSelectRowDefined() ? columnIndex - 1 : columnIndex;
columnIndex = this._isExpandColumnVisible() ? columnIndex - 1 : columnIndex;
if (expandableRow && selectRowAndExpand && (expandBy === _Const2.default.EXPAND_BY_ROW ||
/* Below will allow expanding trigger by clicking on selection column
if configure as expanding by column */
expandBy === _Const2.default.EXPAND_BY_COL && columnIndex < 0 || expandBy === _Const2.default.EXPAND_BY_COL && columns[columnIndex].expandable)) {
(function () {
var rowKey = _this2.props.data[rowIndex - 1][keyField];
var expanding = _this2.props.expanding;
if (expanding.indexOf(rowKey) > -1) {
expanding = expanding.filter(function (k) {
return k !== rowKey;
});
} else {
expanding.push(rowKey);
}
_this2.props.onExpand(expanding);
})();
}
}
}, {
key: '__handleEditCell__REACT_HOT_LOADER__',
value: function __handleEditCell__REACT_HOT_LOADER__(rowIndex, columnIndex, action, e) {
var defineSelectRow = this._isSelectRowDefined();
var expandColumnVisible = this._isExpandColumnVisible();
if (defineSelectRow) {
columnIndex--;
if (this.props.selectRow.hideSelectColumn) columnIndex++;
}
if (expandColumnVisible) {
columnIndex--;
}
rowIndex--;
if (action === 'tab') {
if (defineSelectRow) columnIndex++;
if (expandColumnVisible) columnIndex++;
this.handleCompleteEditCell(e.target.value, rowIndex, columnIndex - 1);
if (columnIndex >= this.props.columns.length) {
this.handleCellKeyDown(e, true);
} else {
this.handleCellKeyDown(e);
}
var _nextEditableCell = this.nextEditableCell(rowIndex, columnIndex),
nextRIndex = _nextEditableCell.nextRIndex,
nextCIndex = _nextEditableCell.nextCIndex;
rowIndex = nextRIndex;
columnIndex = nextCIndex;
}
var stateObj = {
currEditCell: {
rid: rowIndex,
cid: columnIndex
}
};
if (this.props.selectRow.clickToSelectAndEditCell && this.props.cellEdit.mode !== _Const2.default.CELL_EDIT_DBCLICK) {
var selected = this.props.selectedRowKeys.indexOf(this.props.data[rowIndex][this.props.keyField]) !== -1;
this.handleSelectRow(rowIndex + 1, !selected, e);
}
this.setState(stateObj);
}
}, {
key: '__nextEditableCell__REACT_HOT_LOADER__',
value: function __nextEditableCell__REACT_HOT_LOADER__(rIndex, cIndex) {
var keyField = this.props.keyField;
var nextRIndex = rIndex;
var nextCIndex = cIndex;
var row = void 0;
var column = void 0;
do {
if (nextCIndex >= this.props.columns.length) {
nextRIndex++;
nextCIndex = 0;
}
row = this.props.data[nextRIndex];
column = this.props.columns[nextCIndex];
if (!row) break;
var editable = column.editable;
if (isFun(column.editable)) {
editable = column.editable(column, row, nextRIndex, nextCIndex);
}
if (editable && !column.hidden && keyField !== column.name) break;else {
nextCIndex++;
}
} while (row);
return { nextRIndex: nextRIndex, nextCIndex: nextCIndex };
}
}, {
key: '__handleCompleteEditCell__REACT_HOT_LOADER__',
value: function __handleCompleteEditCell__REACT_HOT_LOADER__(newVal, rowIndex, columnIndex) {
this.setState({ currEditCell: null });
if (newVal !== null) {
this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex);
}
}
}, {
key: '__handleClickonSelectColumn__REACT_HOT_LOADER__',
value: function __handleClickonSelectColumn__REACT_HOT_LOADER__(e, isSelect, rowIndex, row) {
e.stopPropagation();
if (e.target.tagName === 'TD' && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell)) {
var unselectable = this.props.selectRow.unselectable || [];
if (unselectable.indexOf(row[this.props.keyField]) === -1) {
this.handleSelectRow(rowIndex + 1, isSelect, e);
this.handleClickCell(rowIndex + 1);
}
}
}
}, {
key: 'renderSelectRowColumn',
value: function renderSelectRowColumn(selected, inputType, disabled) {
var CustomComponent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var _this3 = this;
var rowIndex = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var row = arguments[5];
return _react2.default.createElement(
'td',
{ onClick: function onClick(e) {
_this3.handleClickonSelectColumn(e, !selected, rowIndex, row);
}, style: { textAlign: 'center' } },
CustomComponent ? _react2.default.createElement(CustomComponent, { type: inputType, checked: selected, disabled: disabled,
rowIndex: rowIndex,
onChange: function onChange(e) {
return _this3.handleSelectRowColumChange(e, rowIndex);
} }) : _react2.default.createElement('input', { type: inputType, checked: selected, disabled: disabled,
onChange: function onChange(e) {
return _this3.handleSelectRowColumChange(e, rowIndex);
} })
);
}
}, {
key: 'renderExpandRowColumn',
value: function renderExpandRowColumn(isExpandableRow, isExpanded, CustomComponent) {
var _this4 = this;
var rowIndex = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var content = null;
if (CustomComponent) {
content = _react2.default.createElement(CustomComponent, { isExpandableRow: isExpandableRow, isExpanded: isExpanded });
} else if (isExpandableRow) {
content = isExpanded ? _react2.default.createElement('span', { className: 'glyphicon glyphicon-minus' }) : _react2.default.createElement('span', { className: 'glyphicon glyphicon-plus' });
} else {
content = ' ';
}
return _react2.default.createElement(
'td',
{
className: 'react-bs-table-expand-cell',
onClick: function onClick() {
return _this4.handleClickCell(rowIndex + 1);
} },
content
);
}
}, {
key: '_isSelectRowDefined',
value: function _isSelectRowDefined() {
return this.props.selectRow.mode === _Const2.default.ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2.default.ROW_SELECT_MULTI;
}
}, {
key: '_isExpandColumnVisible',
value: function _isExpandColumnVisible() {
return this.props.expandColumnOptions.expandColumnVisible;
}
}, {
key: '__getHeaderColGrouop__REACT_HOT_LOADER__',
value: function __getHeaderColGrouop__REACT_HOT_LOADER__() {
return this.refs.header.childNodes;
}
}]);
return TableBody;
}(_react.Component);
TableBody.propTypes = {
data: _react.PropTypes.array,
columns: _react.PropTypes.array,
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
keyField: _react.PropTypes.string,
selectedRowKeys: _react.PropTypes.array,
onRowClick: _react.PropTypes.func,
onRowDoubleClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
withoutNoDataText: _react.PropTypes.bool,
style: _react.PropTypes.object,
tableBodyClass: _react.PropTypes.string,
bodyContainerClass: _react.PropTypes.string,
expandableRow: _react.PropTypes.func,
expandComponent: _react.PropTypes.func,
expandRowBgColor: _react.PropTypes.string,
expandBy: _react.PropTypes.string,
expanding: _react.PropTypes.array,
onExpand: _react.PropTypes.func,
beforeShowError: _react.PropTypes.func,
keyBoardNav: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
x: _react.PropTypes.number,
y: _react.PropTypes.number,
onNavigateCell: _react.PropTypes.func
};
var _default = TableBody;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(isFun, 'isFun', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js');
__REACT_HOT_LOADER__.register(TableBody, 'TableBody', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableBody.js');
}();
;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = {
renderReactSortCaret: function renderReactSortCaret(order) {
var orderClass = (0, _classnames2.default)('order', {
'dropup': order === _Const2.default.SORT_ASC
});
return _react2.default.createElement(
'span',
{ className: orderClass },
_react2.default.createElement('span', { className: 'caret', style: { margin: '10px 5px' } })
);
},
getScrollBarWidth: function getScrollBarWidth() {
var inner = document.createElement('p');
inner.style.width = '100%';
inner.style.height = '200px';
var outer = document.createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.left = '0px';
outer.style.visibility = 'hidden';
outer.style.width = '200px';
outer.style.height = '150px';
outer.style.overflow = 'hidden';
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.getBoundingClientRect().width;
outer.style.overflow = 'scroll';
var w2 = inner.getBoundingClientRect().width;
if (w1 === w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return w1 - w2;
},
canUseDOM: function canUseDOM() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
},
renderColGroup: function renderColGroup(columns, selectRow) {
var expandColumnOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var selectRowHeader = null;
var expandRowHeader = null;
var isSelectRowDefined = selectRow.mode === _Const2.default.ROW_SELECT_SINGLE || selectRow.mode === _Const2.default.ROW_SELECT_MULTI;
if (isSelectRowDefined) {
var style = {
width: selectRow.columnWidth || '30px',
minWidth: selectRow.columnWidth || '30px'
};
if (!selectRow.hideSelectColumn) {
selectRowHeader = _react2.default.createElement('col', { key: 'select-col', style: style });
}
}
if (expandColumnOptions.expandColumnVisible) {
var _style = {
width: expandColumnOptions.columnWidth || 30,
minWidth: expandColumnOptions.columnWidth || 30
};
expandRowHeader = _react2.default.createElement('col', { key: 'expand-col', style: _style });
}
var theader = columns.map(function (column, i) {
var style = {
display: column.hidden ? 'none' : null
};
if (column.width) {
var width = !isNaN(column.width) ? column.width + 'px' : column.width;
style.width = width;
/** add min-wdth to fix user assign column width
not eq offsetWidth in large column table **/
style.minWidth = width;
}
return _react2.default.createElement('col', { style: style, key: i, className: column.className });
});
return _react2.default.createElement(
'colgroup',
null,
expandColumnOptions.expandColumnVisible && expandColumnOptions.expandColumnBeforeSelectColumn && expandRowHeader,
selectRowHeader,
expandColumnOptions.expandColumnVisible && !expandColumnOptions.expandColumnBeforeSelectColumn && expandRowHeader,
theader
);
}
}; /* eslint react/display-name: 0 */
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/util.js');
}();
;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-nested-ternary: 0 */
var TableRow = function (_Component) {
_inherits(TableRow, _Component);
function TableRow(props) {
_classCallCheck(this, TableRow);
var _this = _possibleConstructorReturn(this, (TableRow.__proto__ || Object.getPrototypeOf(TableRow)).call(this, props));
_this.rowClick = function () {
return _this.__rowClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.expandRow = function () {
return _this.__expandRow__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.rowDoubleClick = function () {
return _this.__rowDoubleClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.rowMouseOut = function () {
return _this.__rowMouseOut__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.rowMouseOver = function () {
return _this.__rowMouseOver__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.clickNum = 0;
return _this;
}
_createClass(TableRow, [{
key: '__rowClick__REACT_HOT_LOADER__',
value: function __rowClick__REACT_HOT_LOADER__(e) {
var _this2 = this;
var rowIndex = this.props.index + 1;
var cellIndex = e.target.cellIndex;
if (this.props.onRowClick) this.props.onRowClick(rowIndex, cellIndex);
var _props = this.props,
selectRow = _props.selectRow,
unselectableRow = _props.unselectableRow,
isSelected = _props.isSelected,
onSelectRow = _props.onSelectRow,
onExpandRow = _props.onExpandRow;
if (selectRow) {
if (selectRow.clickToSelect && !unselectableRow) {
onSelectRow(rowIndex, !isSelected, e);
} else if (selectRow.clickToSelectAndEditCell && !unselectableRow) {
this.clickNum++;
/** if clickToSelectAndEditCell is enabled,
* there should be a delay to prevent a selection changed when
* user dblick to edit cell on same row but different cell
**/
setTimeout(function () {
if (_this2.clickNum === 1) {
onSelectRow(rowIndex, !isSelected, e);
onExpandRow(rowIndex, cellIndex);
}
_this2.clickNum = 0;
}, 200);
} else {
this.expandRow(rowIndex, cellIndex);
}
}
}
}, {
key: '__expandRow__REACT_HOT_LOADER__',
value: function __expandRow__REACT_HOT_LOADER__(rowIndex, cellIndex) {
var _this3 = this;
this.clickNum++;
setTimeout(function () {
if (_this3.clickNum === 1) {
_this3.props.onExpandRow(rowIndex, cellIndex);
}
_this3.clickNum = 0;
}, 200);
}
}, {
key: '__rowDoubleClick__REACT_HOT_LOADER__',
value: function __rowDoubleClick__REACT_HOT_LOADER__(e) {
if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') {
if (this.props.onRowDoubleClick) {
this.props.onRowDoubleClick(this.props.index);
}
}
}
}, {
key: '__rowMouseOut__REACT_HOT_LOADER__',
value: function __rowMouseOut__REACT_HOT_LOADER__(e) {
var rowIndex = this.props.index;
if (this.props.onRowMouseOut) {
this.props.onRowMouseOut(rowIndex, e);
}
}
}, {
key: '__rowMouseOver__REACT_HOT_LOADER__',
value: function __rowMouseOver__REACT_HOT_LOADER__(e) {
var rowIndex = this.props.index;
if (this.props.onRowMouseOver) {
this.props.onRowMouseOver(rowIndex, e);
}
}
}, {
key: 'render',
value: function render() {
this.clickNum = 0;
var _props2 = this.props,
selectRow = _props2.selectRow,
row = _props2.row,
isSelected = _props2.isSelected;
var backgroundColor = null;
if (selectRow) {
backgroundColor = typeof selectRow.bgColor === 'function' ? selectRow.bgColor(row, isSelected) : isSelected ? selectRow.bgColor : null;
}
var trCss = {
style: { backgroundColor: backgroundColor },
className: (0, _classnames2.default)(isSelected ? selectRow.className : null, this.props.className)
};
return _react2.default.createElement(
'tr',
_extends({}, trCss, {
onMouseOver: this.rowMouseOver,
onMouseOut: this.rowMouseOut,
onClick: this.rowClick,
onDoubleClick: this.rowDoubleClick }),
this.props.children
);
}
}]);
return TableRow;
}(_react.Component);
TableRow.propTypes = {
index: _react.PropTypes.number,
row: _react.PropTypes.any,
isSelected: _react.PropTypes.bool,
enableCellEdit: _react.PropTypes.bool,
onRowClick: _react.PropTypes.func,
onRowDoubleClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
onExpandRow: _react.PropTypes.func,
onRowMouseOut: _react.PropTypes.func,
onRowMouseOver: _react.PropTypes.func,
unselectableRow: _react.PropTypes.bool
};
TableRow.defaultProps = {
onRowClick: undefined,
onRowDoubleClick: undefined
};
var _default = TableRow;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableRow, 'TableRow', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableRow.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableRow.js');
}();
;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TableColumn = function (_Component) {
_inherits(TableColumn, _Component);
function TableColumn(props) {
_classCallCheck(this, TableColumn);
var _this = _possibleConstructorReturn(this, (TableColumn.__proto__ || Object.getPrototypeOf(TableColumn)).call(this, props));
_this.handleCellEdit = function () {
return _this.__handleCellEdit__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleCellClick = function () {
return _this.__handleCellClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleKeyDown = function () {
return _this.__handleKeyDown__REACT_HOT_LOADER__.apply(_this, arguments);
};
return _this;
}
/* eslint no-unused-vars: [0, { "args": "after-used" }] */
_createClass(TableColumn, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var children = this.props.children;
var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || this.props.isFocus !== nextProps.isFocus || (typeof children === 'undefined' ? 'undefined' : _typeof(children)) !== _typeof(nextProps.children) || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString();
if (shouldUpdated) {
return shouldUpdated;
}
if ((typeof children === 'undefined' ? 'undefined' : _typeof(children)) === 'object' && children !== null && children.props !== null) {
if (children.props.type === 'checkbox' || children.props.type === 'radio') {
shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked || children.props.disabled !== nextProps.children.props.disabled;
} else {
shouldUpdated = true;
}
} else {
shouldUpdated = shouldUpdated || children !== nextProps.children;
}
if (shouldUpdated) {
return shouldUpdated;
}
if (!(this.props.cellEdit && nextProps.cellEdit)) {
return false;
} else {
return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode;
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var dom = _reactDom2.default.findDOMNode(this);
if (this.props.isFocus) {
dom.focus();
} else {
dom.blur();
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
var dom = _reactDom2.default.findDOMNode(this);
if (this.props.isFocus) {
dom.focus();
} else {
dom.blur();
}
}
}, {
key: '__handleCellEdit__REACT_HOT_LOADER__',
value: function __handleCellEdit__REACT_HOT_LOADER__(e) {
if (this.props.cellEdit.mode === _Const2.default.CELL_EDIT_DBCLICK) {
if (document.selection && document.selection.empty) {
document.selection.empty();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
this.props.onEdit(this.props.rIndex + 1, e.currentTarget.cellIndex, e);
if (this.props.cellEdit.mode !== _Const2.default.CELL_EDIT_DBCLICK) {
this.props.onClick(this.props.rIndex + 1, e.currentTarget.cellIndex, e);
}
}
}, {
key: '__handleCellClick__REACT_HOT_LOADER__',
value: function __handleCellClick__REACT_HOT_LOADER__(e) {
var _props = this.props,
onClick = _props.onClick,
rIndex = _props.rIndex;
if (onClick) {
onClick(rIndex + 1, e.currentTarget.cellIndex, e);
}
}
}, {
key: '__handleKeyDown__REACT_HOT_LOADER__',
value: function __handleKeyDown__REACT_HOT_LOADER__(e) {
if (this.props.keyBoardNav) {
this.props.onKeyDown(e);
}
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
children = _props2.children,
columnTitle = _props2.columnTitle,
dataAlign = _props2.dataAlign,
hidden = _props2.hidden,
cellEdit = _props2.cellEdit,
attrs = _props2.attrs,
style = _props2.style,
isFocus = _props2.isFocus,
keyBoardNav = _props2.keyBoardNav,
tabIndex = _props2.tabIndex,
customNavStyle = _props2.customNavStyle,
row = _props2.row;
var className = this.props.className;
var tdStyle = _extends({
textAlign: dataAlign,
display: hidden ? 'none' : null
}, style);
var opts = {};
if (cellEdit) {
if (cellEdit.mode === _Const2.default.CELL_EDIT_CLICK) {
opts.onClick = this.handleCellEdit;
} else if (cellEdit.mode === _Const2.default.CELL_EDIT_DBCLICK) {
opts.onDoubleClick = this.handleCellEdit;
} else {
opts.onClick = this.handleCellClick;
}
}
if (keyBoardNav && isFocus) {
opts.onKeyDown = this.handleKeyDown;
}
if (isFocus) {
if (customNavStyle) {
var cusmtStyle = typeof customNavStyle === 'function' ? customNavStyle(children, row) : customNavStyle;
tdStyle = _extends({}, tdStyle, cusmtStyle);
} else {
className = className + ' default-focus-cell';
}
}
return _react2.default.createElement(
'td',
_extends({ tabIndex: tabIndex, style: tdStyle,
title: columnTitle,
className: className
}, opts, attrs),
typeof children === 'boolean' ? children.toString() : children
);
}
}]);
return TableColumn;
}(_react.Component);
TableColumn.propTypes = {
rIndex: _react.PropTypes.number,
dataAlign: _react.PropTypes.string,
hidden: _react.PropTypes.bool,
className: _react.PropTypes.string,
columnTitle: _react.PropTypes.string,
children: _react.PropTypes.node,
onClick: _react.PropTypes.func,
attrs: _react.PropTypes.object,
style: _react.PropTypes.object,
isFocus: _react.PropTypes.bool,
onKeyDown: _react.PropTypes.func,
tabIndex: _react.PropTypes.string,
keyBoardNav: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
customNavStyle: _react.PropTypes.oneOfType([_react.PropTypes.func, _react.PropTypes.object]),
row: _react.PropTypes.any /* only used on custom styling for navigation */
};
TableColumn.defaultProps = {
dataAlign: 'left',
hidden: false,
className: '',
isFocus: false,
keyBoardNav: false
};
var _default = TableColumn;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableColumn, 'TableColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableColumn.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableColumn.js');
}();
;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Editor = __webpack_require__(13);
var _Editor2 = _interopRequireDefault(_Editor);
var _Notification = __webpack_require__(14);
var _Notification2 = _interopRequireDefault(_Notification);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TableEditColumn = function (_Component) {
_inherits(TableEditColumn, _Component);
function TableEditColumn(props) {
_classCallCheck(this, TableEditColumn);
var _this = _possibleConstructorReturn(this, (TableEditColumn.__proto__ || Object.getPrototypeOf(TableEditColumn)).call(this, props));
_this.handleKeyPress = function () {
return _this.__handleKeyPress__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleBlur = function () {
return _this.__handleBlur__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleCustomUpdate = function () {
return _this.__handleCustomUpdate__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.notifyToastr = function () {
return _this.__notifyToastr__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleClick = function () {
return _this.__handleClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.timeouteClear = 0;
var _this$props = _this.props,
fieldValue = _this$props.fieldValue,
row = _this$props.row,
className = _this$props.className;
_this.state = {
shakeEditor: false,
className: typeof className === 'function' ? className(fieldValue, row) : className
};
return _this;
}
_createClass(TableEditColumn, [{
key: '__handleKeyPress__REACT_HOT_LOADER__',
value: function __handleKeyPress__REACT_HOT_LOADER__(e) {
if (e.keyCode === 13) {
// Pressed ENTER
var value = e.currentTarget.type === 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value;
if (!this.validator(value)) {
return;
}
this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
} else if (e.keyCode === 27) {
this.props.completeEdit(null, this.props.rowIndex, this.props.colIndex);
} else if (e.keyCode === 9) {
this.props.onTab(this.props.rowIndex + 1, this.props.colIndex + 1, 'tab', e);
e.preventDefault();
} else if (e.type === 'click' && !this.props.blurToSave) {
// textarea click save button
var _value = e.target.parentElement.firstChild.value;
if (!this.validator(_value)) {
return;
}
this.props.completeEdit(_value, this.props.rowIndex, this.props.colIndex);
}
}
}, {
key: '__handleBlur__REACT_HOT_LOADER__',
value: function __handleBlur__REACT_HOT_LOADER__(e) {
e.stopPropagation();
if (this.props.blurToSave) {
var value = e.currentTarget.type === 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value;
if (!this.validator(value)) {
return;
}
this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
}
}
}, {
key: '__handleCustomUpdate__REACT_HOT_LOADER__',
// modified by iuculanop
// BEGIN
value: function __handleCustomUpdate__REACT_HOT_LOADER__(value) {
if (!this.validator(value)) {
return;
}
this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);
}
}, {
key: 'validator',
value: function validator(value) {
var ts = this;
var valid = true;
if (ts.props.editable.validator) {
var input = ts.refs.inputRef;
var checkVal = ts.props.editable.validator(value, this.props.row);
var responseType = typeof checkVal === 'undefined' ? 'undefined' : _typeof(checkVal);
if (responseType !== 'object' && checkVal !== true) {
valid = false;
this.notifyToastr('error', checkVal, _Const2.default.CANCEL_TOASTR);
} else if (responseType === 'object' && checkVal.isValid !== true) {
valid = false;
this.notifyToastr(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title);
}
if (!valid) {
// animate input
ts.clearTimeout();
var _props = this.props,
invalidColumnClassName = _props.invalidColumnClassName,
row = _props.row;
var className = typeof invalidColumnClassName === 'function' ? invalidColumnClassName(value, row) : invalidColumnClassName;
ts.setState({ shakeEditor: true, className: className });
ts.timeouteClear = setTimeout(function () {
ts.setState({ shakeEditor: false });
}, 300);
input.focus();
return valid;
}
}
return valid;
}
// END
}, {
key: '__notifyToastr__REACT_HOT_LOADER__',
value: function __notifyToastr__REACT_HOT_LOADER__(type, message, title) {
var toastr = true;
var beforeShowError = this.props.beforeShowError;
if (beforeShowError) {
toastr = beforeShowError(type, message, title);
}
if (toastr) {
this.refs.notifier.notice(type, message, title);
}
}
}, {
key: 'clearTimeout',
value: function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
}(function () {
if (this.timeouteClear !== 0) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs.inputRef.focus();
var dom = _reactDom2.default.findDOMNode(this);
if (this.props.isFocus) {
dom.focus();
} else {
dom.blur();
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
var dom = _reactDom2.default.findDOMNode(this);
if (this.props.isFocus) {
dom.focus();
} else {
dom.blur();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: '__handleClick__REACT_HOT_LOADER__',
value: function __handleClick__REACT_HOT_LOADER__(e) {
if (e.target.tagName !== 'TD') {
e.stopPropagation();
}
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
editable = _props2.editable,
format = _props2.format,
customEditor = _props2.customEditor,
isFocus = _props2.isFocus,
customStyleWithNav = _props2.customStyleWithNav,
row = _props2.row;
var shakeEditor = this.state.shakeEditor;
var attr = {
ref: 'inputRef',
onKeyDown: this.handleKeyPress,
onBlur: this.handleBlur
};
var style = { position: 'relative' };
var fieldValue = this.props.fieldValue;
var className = this.state.className;
// put placeholder if exist
editable.placeholder && (attr.placeholder = editable.placeholder);
var editorClass = (0, _classnames2.default)({ 'animated': shakeEditor, 'shake': shakeEditor });
var cellEditor = void 0;
if (customEditor) {
var customEditorProps = _extends({
row: row
}, attr, {
defaultValue: fieldValue || ''
}, customEditor.customEditorParameters);
cellEditor = customEditor.getElement(this.handleCustomUpdate, customEditorProps);
} else {
fieldValue = fieldValue === 0 ? '0' : fieldValue;
cellEditor = (0, _Editor2.default)(editable, attr, format, editorClass, fieldValue || '');
}
if (isFocus) {
if (customStyleWithNav) {
var customStyle = typeof customStyleWithNav === 'function' ? customStyleWithNav(fieldValue, row) : customStyleWithNav;
style = _extends({}, style, customStyle);
} else {
className = className + ' default-focus-cell';
}
}
return _react2.default.createElement(
'td',
{ ref: 'td',
style: style,
className: className,
onClick: this.handleClick },
cellEditor,
_react2.default.createElement(_Notification2.default, { ref: 'notifier' })
);
}
}, {
key: '_getCheckBoxValue',
value: function _getCheckBoxValue(e) {
var value = '';
var values = e.currentTarget.value.split(':');
value = e.currentTarget.checked ? values[0] : values[1];
return value;
}
}]);
return TableEditColumn;
}(_react.Component);
TableEditColumn.propTypes = {
completeEdit: _react.PropTypes.func,
rowIndex: _react.PropTypes.number,
colIndex: _react.PropTypes.number,
blurToSave: _react.PropTypes.bool,
editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
row: _react.PropTypes.any,
fieldValue: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.bool, _react.PropTypes.number, _react.PropTypes.array, _react.PropTypes.object]),
className: _react.PropTypes.any,
beforeShowError: _react.PropTypes.func,
isFocus: _react.PropTypes.bool,
customStyleWithNav: _react.PropTypes.oneOfType([_react.PropTypes.func, _react.PropTypes.object])
};
var _default = TableEditColumn;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableEditColumn, 'TableEditColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableEditColumn.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableEditColumn.js');
}();
;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) {
if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') {
// simple declare
var type = editable ? 'text' : editable;
return _react2.default.createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (!editable) {
var _type = editable ? 'text' : editable;
return _react2.default.createElement('input', _extends({}, attr, { type: _type, defaultValue: defaultValue,
disabled: 'disabled',
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable && (editable.type === undefined || editable.type === null || editable.type.trim() === '')) {
var _type2 = editable ? 'text' : editable;
return _react2.default.createElement('input', _extends({}, attr, { type: _type2, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable.type) {
// standard declare
// put style if exist
editable.style && (attr.style = editable.style);
// put class if exist
attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : '');
if (editable.type === 'select') {
// process select input
var options = [];
var values = editable.options.values;
if (Array.isArray(values)) {
(function () {
// only can use arrray data for options
var rowValue = void 0;
options = values.map(function (d, i) {
rowValue = format ? format(d) : d;
return _react2.default.createElement(
'option',
{ key: 'option' + i, value: d },
rowValue
);
});
})();
}
return _react2.default.createElement(
'select',
_extends({}, attr, { defaultValue: defaultValue }),
options
);
} else if (editable.type === 'textarea') {
var _ret2 = function () {
// process textarea input
// put other if exist
editable.cols && (attr.cols = editable.cols);
editable.rows && (attr.rows = editable.rows);
var saveBtn = void 0;
var keyUpHandler = attr.onKeyDown;
if (keyUpHandler) {
attr.onKeyDown = function (e) {
if (e.keyCode !== 13) {
// not Pressed ENTER
keyUpHandler(e);
}
};
saveBtn = _react2.default.createElement(
'button',
{
className: 'btn btn-info btn-xs textarea-save-btn',
onClick: keyUpHandler },
'save'
);
}
return {
v: _react2.default.createElement(
'div',
null,
_react2.default.createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })),
saveBtn
)
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
} else if (editable.type === 'checkbox') {
var _values = 'true:false';
if (editable.options && editable.options.values) {
// values = editable.options.values.split(':');
_values = editable.options.values;
}
attr.className = attr.className.replace('form-control', '');
attr.className += ' checkbox pull-right';
var checked = defaultValue && defaultValue.toString() === _values.split(':')[0] ? true : false;
return _react2.default.createElement('input', _extends({}, attr, { type: 'checkbox',
value: _values, defaultChecked: checked }));
} else if (editable.type === 'datetime') {
return _react2.default.createElement('input', _extends({}, attr, { type: 'datetime-local', defaultValue: defaultValue }));
} else {
// process other input type. as password,url,email...
return _react2.default.createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue }));
}
}
// default return for other case of editable
return _react2.default.createElement('input', _extends({}, attr, { type: 'text',
className: (editorClass || '') + ' form-control editor edit-text' }));
};
var _default = editor;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(editor, 'editor', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Editor.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Editor.js');
}();
;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactToastr = __webpack_require__(15);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ToastrMessageFactory = _react2.default.createFactory(_reactToastr.ToastMessage.animation);
var Notification = function (_Component) {
_inherits(Notification, _Component);
function Notification() {
_classCallCheck(this, Notification);
return _possibleConstructorReturn(this, (Notification.__proto__ || Object.getPrototypeOf(Notification)).apply(this, arguments));
}
_createClass(Notification, [{
key: 'notice',
// allow type is success,info,warning,error
value: function notice(type, msg, title) {
this.refs.toastr[type](msg, title, {
mode: 'single',
timeOut: 5000,
extendedTimeOut: 1000,
showAnimation: 'animated bounceIn',
hideAnimation: 'animated bounceOut'
});
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_reactToastr.ToastContainer, { ref: 'toastr',
toastMessageFactory: ToastrMessageFactory,
id: 'toast-container',
className: 'toast-top-right' });
}
}]);
return Notification;
}(_react.Component);
var _default = Notification;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(ToastrMessageFactory, 'ToastrMessageFactory', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js');
__REACT_HOT_LOADER__.register(Notification, 'Notification', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Notification.js');
}();
;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToastMessage = exports.ToastContainer = undefined;
var _ToastContainer = __webpack_require__(16);
var _ToastContainer2 = _interopRequireDefault(_ToastContainer);
var _ToastMessage = __webpack_require__(172);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.ToastContainer = _ToastContainer2.default;
exports.ToastMessage = _ToastMessage2.default;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(17);
var _omit3 = _interopRequireDefault(_omit2);
var _includes2 = __webpack_require__(154);
var _includes3 = _interopRequireDefault(_includes2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(165);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _ToastMessage = __webpack_require__(172);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ToastContainer = function (_Component) {
_inherits(ToastContainer, _Component);
function ToastContainer() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, ToastContainer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ToastContainer.__proto__ || Object.getPrototypeOf(ToastContainer)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
toasts: [],
toastId: 0,
messageList: []
}, _this._handle_toast_remove = _this._handle_toast_remove.bind(_this), _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(ToastContainer, [{
key: "error",
value: function error(message, title, optionsOverride) {
this._notify(this.props.toastType.error, message, title, optionsOverride);
}
}, {
key: "info",
value: function info(message, title, optionsOverride) {
this._notify(this.props.toastType.info, message, title, optionsOverride);
}
}, {
key: "success",
value: function success(message, title, optionsOverride) {
this._notify(this.props.toastType.success, message, title, optionsOverride);
}
}, {
key: "warning",
value: function warning(message, title, optionsOverride) {
this._notify(this.props.toastType.warning, message, title, optionsOverride);
}
}, {
key: "clear",
value: function clear() {
var _this2 = this;
Object.keys(this.refs).forEach(function (key) {
_this2.refs[key].hideToast(false);
});
}
}, {
key: "_notify",
value: function _notify(type, message, title) {
var _this3 = this;
var optionsOverride = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (this.props.preventDuplicates) {
if ((0, _includes3.default)(this.state.messageList, message)) {
return;
}
}
var key = this.state.toastId++;
var toastId = key;
var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
$merge: {
type: type,
title: title,
message: message,
toastId: toastId,
key: key,
ref: "toasts__" + key,
handleOnClick: function handleOnClick(e) {
if ("function" === typeof optionsOverride.handleOnClick) {
optionsOverride.handleOnClick();
}
return _this3._handle_toast_on_click(e);
},
handleRemove: this._handle_toast_remove
}
});
var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);
var messageOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [message]);
var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
toasts: toastOperation,
messageList: messageOperation
});
this.setState(nextState);
}
}, {
key: "_handle_toast_on_click",
value: function _handle_toast_on_click(event) {
this.props.onClick(event);
if (event.defaultPrevented) {
return;
}
event.preventDefault();
event.stopPropagation();
}
}, {
key: "_handle_toast_remove",
value: function _handle_toast_remove(toastId) {
var _this4 = this;
if (this.props.preventDuplicates) {
this.state.previousMessage = "";
}
var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
this.state.toasts[operationName](function (found, toast, index) {
if (found || toast.toastId !== toastId) {
return false;
}
_this4.setState((0, _reactAddonsUpdate2.default)(_this4.state, {
toasts: { $splice: [[index, 1]] },
messageList: { $splice: [[index, 1]] }
}));
return true;
}, false);
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var divProps = (0, _omit3.default)(this.props, ["toastType", "toastMessageFactory", "preventDuplicates", "newestOnTop"]);
return _react2.default.createElement(
"div",
_extends({}, divProps, { "aria-live": "polite", role: "alert" }),
this.state.toasts.map(function (toast) {
return _this5.props.toastMessageFactory(toast);
})
);
}
}]);
return ToastContainer;
}(_react.Component);
ToastContainer.propTypes = {
toastType: _react.PropTypes.shape({
error: _react.PropTypes.string,
info: _react.PropTypes.string,
success: _react.PropTypes.string,
warning: _react.PropTypes.string
}).isRequired,
id: _react.PropTypes.string.isRequired,
toastMessageFactory: _react.PropTypes.func.isRequired,
preventDuplicates: _react.PropTypes.bool.isRequired,
newestOnTop: _react.PropTypes.bool.isRequired,
onClick: _react.PropTypes.func.isRequired
};
ToastContainer.defaultProps = {
toastType: {
error: "error",
info: "info",
success: "success",
warning: "warning"
},
id: "toast-container",
toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default.animation),
preventDuplicates: true,
newestOnTop: true,
onClick: function onClick() {}
};
exports.default = ToastContainer;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(18),
baseClone = __webpack_require__(19),
baseUnset = __webpack_require__(129),
castPath = __webpack_require__(130),
copyObject = __webpack_require__(69),
flatRest = __webpack_require__(143),
getAllKeysIn = __webpack_require__(106);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
/***/ },
/* 18 */
/***/ function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(20),
arrayEach = __webpack_require__(64),
assignValue = __webpack_require__(65),
baseAssign = __webpack_require__(68),
baseAssignIn = __webpack_require__(91),
cloneBuffer = __webpack_require__(95),
copyArray = __webpack_require__(96),
copySymbols = __webpack_require__(97),
copySymbolsIn = __webpack_require__(100),
getAllKeys = __webpack_require__(104),
getAllKeysIn = __webpack_require__(106),
getTag = __webpack_require__(107),
initCloneArray = __webpack_require__(112),
initCloneByTag = __webpack_require__(113),
initCloneObject = __webpack_require__(127),
isArray = __webpack_require__(76),
isBuffer = __webpack_require__(77),
isObject = __webpack_require__(44),
keys = __webpack_require__(70);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(21),
stackClear = __webpack_require__(29),
stackDelete = __webpack_require__(30),
stackGet = __webpack_require__(31),
stackHas = __webpack_require__(32),
stackSet = __webpack_require__(33);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(22),
listCacheDelete = __webpack_require__(23),
listCacheGet = __webpack_require__(26),
listCacheHas = __webpack_require__(27),
listCacheSet = __webpack_require__(28);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ },
/* 22 */
/***/ function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(24);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(25);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ },
/* 25 */
/***/ function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(24);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(24);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(24);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(21);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ },
/* 30 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ },
/* 31 */
/***/ function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ },
/* 32 */
/***/ function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(21),
Map = __webpack_require__(34),
MapCache = __webpack_require__(49);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(40);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(36),
getValue = __webpack_require__(48);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(37),
isMasked = __webpack_require__(45),
isObject = __webpack_require__(44),
toSource = __webpack_require__(47);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(38),
isObject = __webpack_require__(44);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
getRawTag = __webpack_require__(42),
objectToString = __webpack_require__(43);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
value = Object(value);
return (symToStringTag && symToStringTag in value)
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(40);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(41);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ },
/* 41 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39);
/** Used for built-in 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/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ },
/* 43 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ },
/* 44 */
/***/ function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(46);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(40);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ },
/* 47 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ },
/* 48 */
/***/ function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(50),
mapCacheDelete = __webpack_require__(58),
mapCacheGet = __webpack_require__(61),
mapCacheHas = __webpack_require__(62),
mapCacheSet = __webpack_require__(63);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(51),
ListCache = __webpack_require__(21),
Map = __webpack_require__(34);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(52),
hashDelete = __webpack_require__(54),
hashGet = __webpack_require__(55),
hashHas = __webpack_require__(56),
hashSet = __webpack_require__(57);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(53);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ },
/* 54 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(53);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(53);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(53);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(59);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(60);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ },
/* 60 */
/***/ function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(59);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(59);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(59);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ },
/* 64 */
/***/ function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(66),
eq = __webpack_require__(25);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(67);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(69),
keys = __webpack_require__(70);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(65),
baseAssignValue = __webpack_require__(66);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(71),
baseKeys = __webpack_require__(86),
isArrayLike = __webpack_require__(90);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(72),
isArguments = __webpack_require__(73),
isArray = __webpack_require__(76),
isBuffer = __webpack_require__(77),
isIndex = __webpack_require__(80),
isTypedArray = __webpack_require__(81);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ },
/* 72 */
/***/ function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(74),
isObjectLike = __webpack_require__(75);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(38),
isObjectLike = __webpack_require__(75);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ },
/* 75 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 76 */
/***/ function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(40),
stubFalse = __webpack_require__(79);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module)))
/***/ },
/* 78 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 79 */
/***/ function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ },
/* 80 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(82),
baseUnary = __webpack_require__(84),
nodeUtil = __webpack_require__(85);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(38),
isLength = __webpack_require__(83),
isObjectLike = __webpack_require__(75);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ },
/* 83 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ },
/* 84 */
/***/ function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(41);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module)))
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(87),
nativeKeys = __webpack_require__(88);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ },
/* 87 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(89);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ },
/* 89 */
/***/ function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(37),
isLength = __webpack_require__(83);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(69),
keysIn = __webpack_require__(92);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(71),
baseKeysIn = __webpack_require__(93),
isArrayLike = __webpack_require__(90);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(44),
isPrototype = __webpack_require__(87),
nativeKeysIn = __webpack_require__(94);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ },
/* 94 */
/***/ function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(40);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(78)(module)))
/***/ },
/* 96 */
/***/ function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(69),
getSymbols = __webpack_require__(98);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(89),
stubArray = __webpack_require__(99);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
module.exports = getSymbols;
/***/ },
/* 99 */
/***/ function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(69),
getSymbolsIn = __webpack_require__(101);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(102),
getPrototype = __webpack_require__(103),
getSymbols = __webpack_require__(98),
stubArray = __webpack_require__(99);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ },
/* 102 */
/***/ function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(89);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(105),
getSymbols = __webpack_require__(98),
keys = __webpack_require__(70);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(102),
isArray = __webpack_require__(76);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(105),
getSymbolsIn = __webpack_require__(101),
keysIn = __webpack_require__(92);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(108),
Map = __webpack_require__(34),
Promise = __webpack_require__(109),
Set = __webpack_require__(110),
WeakMap = __webpack_require__(111),
baseGetTag = __webpack_require__(38),
toSource = __webpack_require__(47);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(40);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(40);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(40);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(40);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ },
/* 112 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(114),
cloneDataView = __webpack_require__(116),
cloneMap = __webpack_require__(117),
cloneRegExp = __webpack_require__(121),
cloneSet = __webpack_require__(122),
cloneSymbol = __webpack_require__(125),
cloneTypedArray = __webpack_require__(126);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(115);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(40);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(114);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(118),
arrayReduce = __webpack_require__(119),
mapToArray = __webpack_require__(120);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
module.exports = cloneMap;
/***/ },
/* 118 */
/***/ function(module, exports) {
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ },
/* 119 */
/***/ function(module, exports) {
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ },
/* 120 */
/***/ function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ },
/* 121 */
/***/ function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(123),
arrayReduce = __webpack_require__(119),
setToArray = __webpack_require__(124);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
module.exports = cloneSet;
/***/ },
/* 123 */
/***/ function(module, exports) {
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(114);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(128),
getPrototype = __webpack_require__(103),
isPrototype = __webpack_require__(87);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(44);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(130),
last = __webpack_require__(138),
parent = __webpack_require__(139),
toKey = __webpack_require__(141);
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(76),
isKey = __webpack_require__(131),
stringToPath = __webpack_require__(133),
toString = __webpack_require__(136);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(76),
isSymbol = __webpack_require__(132);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(38),
isObjectLike = __webpack_require__(75);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(134);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(135);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(49);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(137);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
arrayMap = __webpack_require__(18),
isArray = __webpack_require__(76),
isSymbol = __webpack_require__(132);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ },
/* 138 */
/***/ function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(140),
baseSlice = __webpack_require__(142);
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(130),
toKey = __webpack_require__(141);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(132);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ },
/* 142 */
/***/ function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(144),
overRest = __webpack_require__(147),
setToString = __webpack_require__(149);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(145);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(102),
isFlattenable = __webpack_require__(146);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
isArguments = __webpack_require__(73),
isArray = __webpack_require__(76);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(148);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ },
/* 148 */
/***/ function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(150),
shortOut = __webpack_require__(153);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
var constant = __webpack_require__(151),
defineProperty = __webpack_require__(67),
identity = __webpack_require__(152);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ },
/* 151 */
/***/ function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ },
/* 152 */
/***/ function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ },
/* 153 */
/***/ function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(155),
isArrayLike = __webpack_require__(90),
isString = __webpack_require__(159),
toInteger = __webpack_require__(160),
values = __webpack_require__(163);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(156),
baseIsNaN = __webpack_require__(157),
strictIndexOf = __webpack_require__(158);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ },
/* 156 */
/***/ function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ },
/* 157 */
/***/ function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ },
/* 158 */
/***/ function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(38),
isArray = __webpack_require__(76),
isObjectLike = __webpack_require__(75);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(161);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(162);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(44),
isSymbol = __webpack_require__(132);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(164),
keys = __webpack_require__(70);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(18);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(166);
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var _prodInvariant = __webpack_require__(168),
_assign = __webpack_require__(169);
var keyOf = __webpack_require__(170);
var invariant = __webpack_require__(171);
var hasOwnProperty = {}.hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return _assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({ $push: null });
var COMMAND_UNSHIFT = keyOf({ $unshift: null });
var COMMAND_SPLICE = keyOf({ $splice: null });
var COMMAND_SET = keyOf({ $set: null });
var COMMAND_MERGE = keyOf({ $merge: null });
var COMMAND_APPLY = keyOf({ $apply: null });
var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function (command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : _prodInvariant('1', command, value) : void 0;
var specValue = spec[command];
!Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. Did you forget to wrap your parameter in an array?', command, specValue) : _prodInvariant('2', command, specValue) : void 0;
}
/**
* Returns a updated shallow copy of an object without mutating the original.
* See https://facebook.github.io/react/docs/update.html for details.
*/
function update(value, spec) {
!(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0;
if (hasOwnProperty.call(spec, COMMAND_SET)) {
!(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _prodInvariant('4', COMMAND_SET) : void 0;
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
!(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : _prodInvariant('5', COMMAND_MERGE, mergeObj) : void 0;
!(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : _prodInvariant('6', COMMAND_MERGE, nextValue) : void 0;
_assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function (item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function (item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : _prodInvariant('7', COMMAND_SPLICE, value) : void 0;
!Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0;
spec[COMMAND_SPLICE].forEach(function (args) {
!Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0;
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
!(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : _prodInvariant('9', COMMAND_APPLY, spec[COMMAND_APPLY]) : void 0;
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(167)))
/***/ },
/* 167 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 168 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule reactProdInvariant
*
*/
'use strict';
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
module.exports = reactProdInvariant;
/***/ },
/* 169 */
/***/ function(module, exports) {
'use strict';
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 170 */
/***/ function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function keyOf(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(167)))
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.jQuery = exports.animation = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(165);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _animationMixin = __webpack_require__(173);
var _animationMixin2 = _interopRequireDefault(_animationMixin);
var _jQueryMixin = __webpack_require__(178);
var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function noop() {}
var ToastMessageSpec = {
displayName: "ToastMessage",
getDefaultProps: function getDefaultProps() {
var iconClassNames = {
error: "toast-error",
info: "toast-info",
success: "toast-success",
warning: "toast-warning"
};
return {
className: "toast",
iconClassNames: iconClassNames,
titleClassName: "toast-title",
messageClassName: "toast-message",
tapToDismiss: true,
closeButton: false
};
},
handleOnClick: function handleOnClick(event) {
this.props.handleOnClick(event);
if (this.props.tapToDismiss) {
this.hideToast(true);
}
},
_handle_close_button_click: function _handle_close_button_click(event) {
event.stopPropagation();
this.hideToast(true);
},
_handle_remove: function _handle_remove() {
this.props.handleRemove(this.props.toastId);
},
_render_close_button: function _render_close_button() {
return this.props.closeButton ? _react2.default.createElement("button", {
className: "toast-close-button", role: "button",
onClick: this._handle_close_button_click,
dangerouslySetInnerHTML: { __html: "×" }
}) : false;
},
_render_title_element: function _render_title_element() {
return this.props.title ? _react2.default.createElement(
"div",
{ className: this.props.titleClassName },
this.props.title
) : false;
},
_render_message_element: function _render_message_element() {
return this.props.message ? _react2.default.createElement(
"div",
{ className: this.props.messageClassName },
this.props.message
) : false;
},
render: function render() {
var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type];
return _react2.default.createElement(
"div",
{
className: (0, _classnames2.default)(this.props.className, iconClassName),
style: this.props.style,
onClick: this.handleOnClick,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave
},
this._render_close_button(),
this._render_title_element(),
this._render_message_element()
);
}
};
var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.animation" },
mixins: { $set: [_animationMixin2.default] }
}));
var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.jQuery" },
mixins: { $set: [_jQueryMixin2.default] }
}));
/*
* assign default noop functions
*/
ToastMessageSpec.handleMouseEnter = noop;
ToastMessageSpec.handleMouseLeave = noop;
ToastMessageSpec.hideToast = noop;
var ToastMessage = _react2.default.createClass(ToastMessageSpec);
ToastMessage.animation = animation;
ToastMessage.jQuery = jQuery;
exports.default = ToastMessage;
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ReactTransitionEvents = __webpack_require__(174);
var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _elementClass = __webpack_require__(177);
var _elementClass2 = _interopRequireDefault(_elementClass);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TICK = 17;
var toString = Object.prototype.toString;
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate)
showAnimation: "animated bounceIn", // or other animations from animate.css
hideAnimation: "animated bounceOut",
timeOut: 5000,
extendedTimeOut: 1000
};
},
componentWillMount: function componentWillMount() {
this.classNameQueue = [];
this.isHiding = false;
this.intervalId = null;
},
componentDidMount: function componentDidMount() {
var _this = this;
this._is_mounted = true;
this._show();
var node = _reactDom2.default.findDOMNode(this);
var onHideComplete = function onHideComplete() {
if (_this.isHiding) {
_this._set_is_hiding(false);
_ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete);
_this._handle_remove();
}
};
_ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
componentWillUnmount: function componentWillUnmount() {
this._is_mounted = false;
if (this.intervalId) {
clearTimeout(this.intervalId);
}
},
_set_transition: function _set_transition(hide) {
var animationType = hide ? "leave" : "enter";
var node = _reactDom2.default.findDOMNode(this);
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
var classList = (0, _elementClass2.default)(node);
classList.remove(className);
classList.remove(activeClassName);
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
(0, _elementClass2.default)(node).add(className);
// Need to do this to actually trigger a transition.
this._queue_class(activeClassName);
},
_clear_transition: function _clear_transition(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animationType = hide ? "leave" : "enter";
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
var classList = (0, _elementClass2.default)(node);
classList.remove(className);
classList.remove(activeClassName);
},
_set_animation: function _set_animation(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animations = this._get_animation_classes(hide);
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
animations.forEach(function (anim) {
return (0, _elementClass2.default)(node).remove(anim);
});
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
animations.forEach(function (anim) {
return (0, _elementClass2.default)(node).add(anim);
});
},
_get_animation_classes: function _get_animation_classes(hide) {
var animations = hide ? this.props.hideAnimation : this.props.showAnimation;
if ("[object Array]" === toString.call(animations)) {
return animations;
} else if ("string" === typeof animations) {
return animations.split(" ");
}
},
_clear_animation: function _clear_animation(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animations = this._get_animation_classes(hide);
animations.forEach(function (animation) {
return (0, _elementClass2.default)(node).remove(animation);
});
},
_queue_class: function _queue_class(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this._flush_class_name_queue, TICK);
}
},
_flush_class_name_queue: function _flush_class_name_queue() {
var _this2 = this;
if (this._is_mounted) {
(function () {
var node = _reactDom2.default.findDOMNode(_this2);
_this2.classNameQueue.forEach(function (className) {
return (0, _elementClass2.default)(node).add(className);
});
})();
}
this.classNameQueue.length = 0;
this.timeout = null;
},
_show: function _show() {
if (this.props.transition) {
this._set_transition();
} else if (this.props.showAnimation) {
this._set_animation();
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.intervalId);
this._set_interval_id(null);
if (this.isHiding) {
this._set_is_hiding(false);
if (this.props.hideAnimation) {
this._clear_animation(true);
} else if (this.props.transition) {
this._clear_transition(true);
}
}
},
handleMouseLeave: function handleMouseLeave() {
if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.isHiding || this.intervalId === null && !override) {
return;
}
this._set_is_hiding(true);
if (this.props.transition) {
this._set_transition(true);
} else if (this.props.hideAnimation) {
this._set_animation(true);
} else {
this._handle_remove();
}
},
_set_interval_id: function _set_interval_id(intervalId) {
this.intervalId = intervalId;
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.isHiding = isHiding;
}
};
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(175);
var getVendorPrefixedEventName = __webpack_require__(176);
var endEvents = [];
function detectEvents() {
var animEnd = getVendorPrefixedEventName('animationend');
var transEnd = getVendorPrefixedEventName('transitionend');
if (animEnd) {
endEvents.push(animEnd);
}
if (transEnd) {
endEvents.push(transEnd);
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
/***/ },
/* 175 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var 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;
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getVendorPrefixedEventName
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(175);
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
}
module.exports = getVendorPrefixedEventName;
/***/ },
/* 177 */
/***/ function(module, exports) {
module.exports = function(opts) {
return new ElementClass(opts)
}
function indexOf(arr, prop) {
if (arr.indexOf) return arr.indexOf(prop)
for (var i = 0, len = arr.length; i < len; i++)
if (arr[i] === prop) return i
return -1
}
function ElementClass(opts) {
if (!(this instanceof ElementClass)) return new ElementClass(opts)
var self = this
if (!opts) opts = {}
// similar doing instanceof HTMLElement but works in IE8
if (opts.nodeType) opts = {el: opts}
this.opts = opts
this.el = opts.el || document.body
if (typeof this.el !== 'object') this.el = document.querySelector(this.el)
}
ElementClass.prototype.add = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return el.className = className
var classes = el.className.split(' ')
if (indexOf(classes, className) > -1) return classes
classes.push(className)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.remove = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return
var classes = el.className.split(' ')
var idx = indexOf(classes, className)
if (idx > -1) classes.splice(idx, 1)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.has = function(className) {
var el = this.el
if (!el) return
var classes = el.className.split(' ')
return indexOf(classes, className) > -1
}
ElementClass.prototype.toggle = function(className) {
var el = this.el
if (!el) return
if (this.has(className)) this.remove(className)
else this.add(className)
}
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call_show_method($node, props) {
$node[props.showMethod]({
duration: props.showDuration,
easing: props.showEasing
});
}
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
style: {
display: "none" },
showMethod: "fadeIn", // slideDown, and show are built into jQuery
showDuration: 300,
showEasing: "swing", // and linear are built into jQuery
hideMethod: "fadeOut",
hideDuration: 1000,
hideEasing: "swing",
//
timeOut: 5000,
extendedTimeOut: 1000
};
},
getInitialState: function getInitialState() {
return {
intervalId: null,
isHiding: false
};
},
componentDidMount: function componentDidMount() {
call_show_method(this._get_$_node(), this.props);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.state.intervalId);
this._set_interval_id(null);
this._set_is_hiding(false);
call_show_method(this._get_$_node().stop(true, true), this.props);
},
handleMouseLeave: function handleMouseLeave() {
if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.state.isHiding || this.state.intervalId === null && !override) {
return;
}
this.setState({ isHiding: true });
this._get_$_node()[this.props.hideMethod]({
duration: this.props.hideDuration,
easing: this.props.hideEasing,
complete: this._handle_remove
});
},
_get_$_node: function _get_$_node() {
/* eslint-disable no-undef */
return jQuery(_reactDom2.default.findDOMNode(this));
/* eslint-enable no-undef */
},
_set_interval_id: function _set_interval_id(intervalId) {
this.setState({
intervalId: intervalId
});
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.setState({
isHiding: isHiding
});
}
};
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-len: 0 */
var ExpandComponent = function (_Component) {
_inherits(ExpandComponent, _Component);
function ExpandComponent() {
_classCallCheck(this, ExpandComponent);
return _possibleConstructorReturn(this, (ExpandComponent.__proto__ || Object.getPrototypeOf(ExpandComponent)).apply(this, arguments));
}
_createClass(ExpandComponent, [{
key: 'render',
value: function render() {
var trCss = {
style: {
backgroundColor: this.props.bgColor
},
className: (0, _classnames2.default)(this.props.isSelected ? this.props.selectRow.className : null, this.props.className)
};
return _react2.default.createElement(
'tr',
_extends({ hidden: this.props.hidden, width: this.props.width }, trCss),
_react2.default.createElement(
'td',
{ colSpan: this.props.colSpan },
this.props.children
)
);
}
}]);
return ExpandComponent;
}(_react.Component);
var _default = ExpandComponent;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(ExpandComponent, 'ExpandComponent', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/ExpandComponent.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/ExpandComponent.js');
}();
;
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _PageButton = __webpack_require__(181);
var _PageButton2 = _interopRequireDefault(_PageButton);
var _SizePerPageDropDown = __webpack_require__(182);
var _SizePerPageDropDown2 = _interopRequireDefault(_SizePerPageDropDown);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var PaginationList = function (_Component) {
_inherits(PaginationList, _Component);
function PaginationList(props) {
_classCallCheck(this, PaginationList);
var _this = _possibleConstructorReturn(this, (PaginationList.__proto__ || Object.getPrototypeOf(PaginationList)).call(this, props));
_this.changePage = function () {
return _this.__changePage__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.changeSizePerPage = function () {
return _this.__changeSizePerPage__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.toggleDropDown = function () {
return _this.__toggleDropDown__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.state = {
open: _this.props.open
};
return _this;
}
_createClass(PaginationList, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps() {
this.setState({ open: false });
}
}, {
key: '__changePage__REACT_HOT_LOADER__',
value: function __changePage__REACT_HOT_LOADER__(page) {
var _props = this.props,
pageStartIndex = _props.pageStartIndex,
prePage = _props.prePage,
currPage = _props.currPage,
nextPage = _props.nextPage,
lastPage = _props.lastPage,
firstPage = _props.firstPage,
sizePerPage = _props.sizePerPage;
if (page === prePage) {
page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1;
} else if (page === nextPage) {
page = currPage + 1 > this.lastPage ? this.lastPage : currPage + 1;
} else if (page === lastPage) {
page = this.lastPage;
} else if (page === firstPage) {
page = pageStartIndex;
} else {
page = parseInt(page, 10);
}
if (page !== currPage) {
this.props.changePage(page, sizePerPage);
}
}
}, {
key: '__changeSizePerPage__REACT_HOT_LOADER__',
value: function __changeSizePerPage__REACT_HOT_LOADER__(pageNum) {
var selectSize = typeof pageNum === 'string' ? parseInt(pageNum, 10) : pageNum;
var currPage = this.props.currPage;
if (selectSize !== this.props.sizePerPage) {
this.totalPages = Math.ceil(this.props.dataSize / selectSize);
this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
if (currPage > this.lastPage) currPage = this.lastPage;
this.props.changePage(currPage, selectSize);
if (this.props.onSizePerPageList) {
this.props.onSizePerPageList(selectSize);
}
} else {
this.setState({ open: false });
}
}
}, {
key: '__toggleDropDown__REACT_HOT_LOADER__',
value: function __toggleDropDown__REACT_HOT_LOADER__() {
this.setState({
open: !this.state.open
});
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
currPage = _props2.currPage,
dataSize = _props2.dataSize,
sizePerPage = _props2.sizePerPage,
sizePerPageList = _props2.sizePerPageList,
paginationShowsTotal = _props2.paginationShowsTotal,
pageStartIndex = _props2.pageStartIndex,
paginationPanel = _props2.paginationPanel,
hidePageListOnlyOnePage = _props2.hidePageListOnlyOnePage;
this.totalPages = Math.ceil(dataSize / sizePerPage);
this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
var pageBtns = this.makePage(typeof paginationPanel === 'function');
var dropdown = this.makeDropDown();
var offset = Math.abs(_Const2.default.PAGE_START_INDEX - pageStartIndex);
var start = (currPage - pageStartIndex) * sizePerPage;
start = dataSize === 0 ? 0 : start + 1;
var to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize);
if (to >= dataSize) to--;
var total = paginationShowsTotal ? _react2.default.createElement(
'span',
null,
'Showing rows ',
start,
' to\xA0',
to + 1,
' of\xA0',
dataSize
) : null;
if (typeof paginationShowsTotal === 'function') {
total = paginationShowsTotal(start, to + 1, dataSize);
}
var content = paginationPanel && paginationPanel({
currPage: currPage,
sizePerPage: sizePerPage,
sizePerPageList: sizePerPageList,
pageStartIndex: pageStartIndex,
changePage: this.changePage,
toggleDropDown: this.toggleDropDown,
changeSizePerPage: this.changeSizePerPage,
components: {
totalText: total,
sizePerPageDropdown: dropdown,
pageList: pageBtns
}
});
var hidePageList = hidePageListOnlyOnePage && this.totalPages === 1 ? 'none' : 'block';
return _react2.default.createElement(
'div',
{ className: 'row', style: { marginTop: 15 } },
content || _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'div',
{ className: 'col-md-6 col-xs-6 col-sm-6 col-lg-6' },
total,
sizePerPageList.length > 1 ? dropdown : null
),
_react2.default.createElement(
'div',
{ style: { display: hidePageList },
className: 'col-md-6 col-xs-6 col-sm-6 col-lg-6' },
pageBtns
)
)
);
}
}, {
key: 'makeDropDown',
value: function makeDropDown() {
var _this2 = this;
var dropdown = void 0;
var dropdownProps = void 0;
var sizePerPageText = '';
var _props3 = this.props,
sizePerPageDropDown = _props3.sizePerPageDropDown,
hideSizePerPage = _props3.hideSizePerPage,
sizePerPage = _props3.sizePerPage,
sizePerPageList = _props3.sizePerPageList;
if (sizePerPageDropDown) {
dropdown = sizePerPageDropDown({
open: this.state.open,
hideSizePerPage: hideSizePerPage,
currSizePerPage: sizePerPage,
sizePerPageList: sizePerPageList,
toggleDropDown: this.toggleDropDown,
changeSizePerPage: this.changeSizePerPage
});
if (dropdown.type.name === _SizePerPageDropDown2.default.name) {
dropdownProps = dropdown.props;
} else {
return dropdown;
}
}
if (dropdownProps || !dropdown) {
var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) {
var pageText = _sizePerPage.text || _sizePerPage;
var pageNum = _sizePerPage.value || _sizePerPage;
if (sizePerPage === pageNum) sizePerPageText = pageText;
return _react2.default.createElement(
'li',
{ key: pageText, role: 'presentation' },
_react2.default.createElement(
'a',
{ role: 'menuitem',
tabIndex: '-1', href: '#',
'data-page': pageNum,
onClick: function onClick(e) {
e.preventDefault();
_this2.changeSizePerPage(pageNum);
} },
pageText
)
);
});
dropdown = _react2.default.createElement(_SizePerPageDropDown2.default, _extends({
open: this.state.open,
hidden: hideSizePerPage,
currSizePerPage: String(sizePerPageText),
options: sizePerPageOptions,
onClick: this.toggleDropDown
}, dropdownProps));
}
return dropdown;
}
}, {
key: 'makePage',
value: function makePage() {
var _this3 = this;
var isCustomPagingPanel = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var pages = this.getPages();
var isStart = function isStart(page, _ref) {
var currPage = _ref.currPage,
pageStartIndex = _ref.pageStartIndex,
firstPage = _ref.firstPage,
prePage = _ref.prePage;
return currPage === pageStartIndex && (page === firstPage || page === prePage);
};
var isEnd = function isEnd(page, _ref2) {
var currPage = _ref2.currPage,
nextPage = _ref2.nextPage,
lastPage = _ref2.lastPage;
return currPage === _this3.lastPage && (page === nextPage || page === lastPage);
};
var pageBtns = pages.filter(function (page) {
if (this.props.alwaysShowAllBtns) {
return true;
}
return isStart(page, this.props) || isEnd(page, this.props) ? false : true;
}, this).map(function (page) {
var isActive = page === this.props.currPage;
var isDisabled = isStart(page, this.props) || isEnd(page, this.props) ? true : false;
var title = page + '';
if (page === this.props.nextPage) {
title = this.props.nextPageTitle;
} else if (page === this.props.prePage) {
title = this.props.prePageTitle;
} else if (page === this.props.firstPage) {
title = this.props.firstPageTitle;
} else if (page === this.props.lastPage) {
title = this.props.lastPageTitle;
}
return _react2.default.createElement(
_PageButton2.default,
{ key: page,
title: title,
changePage: this.changePage,
active: isActive,
disable: isDisabled },
page
);
}, this);
var classname = (0, _classnames2.default)(isCustomPagingPanel ? null : 'react-bootstrap-table-page-btns-ul', 'pagination');
return _react2.default.createElement(
'ul',
{ className: classname },
pageBtns
);
}
}, {
key: 'getLastPage',
value: function getLastPage() {
return this.lastPage;
}
}, {
key: 'getPages',
value: function getPages() {
var pages = void 0;
var endPage = this.totalPages;
if (endPage <= 0) return [];
var startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), this.props.pageStartIndex);
endPage = startPage + this.props.paginationSize - 1;
if (endPage > this.lastPage) {
endPage = this.lastPage;
startPage = endPage - this.props.paginationSize + 1;
}
if (startPage !== this.props.pageStartIndex && this.totalPages > this.props.paginationSize && this.props.withFirstAndLast) {
pages = [this.props.firstPage, this.props.prePage];
} else if (this.totalPages > 1 || this.props.alwaysShowAllBtns) {
pages = [this.props.prePage];
} else {
pages = [];
}
for (var i = startPage; i <= endPage; i++) {
if (i >= this.props.pageStartIndex) pages.push(i);
}
if (endPage <= this.lastPage) {
pages.push(this.props.nextPage);
}
if (endPage !== this.totalPages && this.props.withFirstAndLast) {
pages.push(this.props.lastPage);
}
return pages;
}
}]);
return PaginationList;
}(_react.Component);
PaginationList.propTypes = {
currPage: _react.PropTypes.number,
sizePerPage: _react.PropTypes.number,
dataSize: _react.PropTypes.number,
changePage: _react.PropTypes.func,
sizePerPageList: _react.PropTypes.array,
paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
paginationSize: _react.PropTypes.number,
onSizePerPageList: _react.PropTypes.func,
prePage: _react.PropTypes.string,
pageStartIndex: _react.PropTypes.number,
hideSizePerPage: _react.PropTypes.bool,
alwaysShowAllBtns: _react.PropTypes.bool,
withFirstAndLast: _react.PropTypes.bool,
sizePerPageDropDown: _react.PropTypes.func,
paginationPanel: _react.PropTypes.func,
prePageTitle: _react.PropTypes.string,
nextPageTitle: _react.PropTypes.string,
firstPageTitle: _react.PropTypes.string,
lastPageTitle: _react.PropTypes.string,
hidePageListOnlyOnePage: _react.PropTypes.bool
};
PaginationList.defaultProps = {
sizePerPage: _Const2.default.SIZE_PER_PAGE,
pageStartIndex: _Const2.default.PAGE_START_INDEX
};
var _default = PaginationList;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(PaginationList, 'PaginationList', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PaginationList.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PaginationList.js');
}();
;
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var PageButton = function (_Component) {
_inherits(PageButton, _Component);
function PageButton(props) {
_classCallCheck(this, PageButton);
var _this = _possibleConstructorReturn(this, (PageButton.__proto__ || Object.getPrototypeOf(PageButton)).call(this, props));
_this.pageBtnClick = function () {
return _this.__pageBtnClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
return _this;
}
_createClass(PageButton, [{
key: '__pageBtnClick__REACT_HOT_LOADER__',
value: function __pageBtnClick__REACT_HOT_LOADER__(e) {
e.preventDefault();
this.props.changePage(e.currentTarget.textContent);
}
}, {
key: 'render',
value: function render() {
var classes = (0, _classnames2.default)({
'active': this.props.active,
'disabled': this.props.disable,
'hidden': this.props.hidden,
'page-item': true
});
return _react2.default.createElement(
'li',
{ className: classes, title: this.props.title },
_react2.default.createElement(
'a',
{ href: '#', onClick: this.pageBtnClick, className: 'page-link' },
this.props.children
)
);
}
}]);
return PageButton;
}(_react.Component);
PageButton.propTypes = {
title: _react.PropTypes.string,
changePage: _react.PropTypes.func,
active: _react.PropTypes.bool,
disable: _react.PropTypes.bool,
hidden: _react.PropTypes.bool,
children: _react.PropTypes.node
};
var _default = PageButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(PageButton, 'PageButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PageButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/PageButton.js');
}();
;
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SizePerPageDropDown = function (_Component) {
_inherits(SizePerPageDropDown, _Component);
function SizePerPageDropDown() {
_classCallCheck(this, SizePerPageDropDown);
return _possibleConstructorReturn(this, (SizePerPageDropDown.__proto__ || Object.getPrototypeOf(SizePerPageDropDown)).apply(this, arguments));
}
_createClass(SizePerPageDropDown, [{
key: 'render',
value: function render() {
var _props = this.props,
open = _props.open,
hidden = _props.hidden,
onClick = _props.onClick,
options = _props.options,
className = _props.className,
variation = _props.variation,
btnContextual = _props.btnContextual,
currSizePerPage = _props.currSizePerPage;
var openClass = open ? 'open' : '';
var dropDownStyle = { visibility: hidden ? 'hidden' : 'visible' };
return _react2.default.createElement(
'span',
{ className: variation + ' ' + openClass + ' ' + className, style: dropDownStyle },
_react2.default.createElement(
'button',
{ className: 'btn ' + btnContextual + ' dropdown-toggle',
id: 'pageDropDown', 'data-toggle': 'dropdown',
'aria-expanded': open,
onClick: onClick },
currSizePerPage,
_react2.default.createElement(
'span',
null,
' ',
_react2.default.createElement('span', { className: 'caret' })
)
),
_react2.default.createElement(
'ul',
{ className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' },
options
)
);
}
}]);
return SizePerPageDropDown;
}(_react.Component);
SizePerPageDropDown.propTypes = {
open: _react.PropTypes.bool,
hidden: _react.PropTypes.bool,
btnContextual: _react.PropTypes.string,
currSizePerPage: _react.PropTypes.string,
options: _react.PropTypes.array,
variation: _react.PropTypes.oneOf(['dropdown', 'dropup']),
className: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
SizePerPageDropDown.defaultProps = {
open: false,
hidden: false,
btnContextual: 'btn-default',
variation: 'dropdown',
className: ''
};
var _default = SizePerPageDropDown;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(SizePerPageDropDown, 'SizePerPageDropDown', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/SizePerPageDropDown.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/pagination/SizePerPageDropDown.js');
}();
;
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactModal = __webpack_require__(184);
var _reactModal2 = _interopRequireDefault(_reactModal);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _Notification = __webpack_require__(14);
var _Notification2 = _interopRequireDefault(_Notification);
var _InsertModal = __webpack_require__(194);
var _InsertModal2 = _interopRequireDefault(_InsertModal);
var _InsertButton = __webpack_require__(198);
var _InsertButton2 = _interopRequireDefault(_InsertButton);
var _DeleteButton = __webpack_require__(199);
var _DeleteButton2 = _interopRequireDefault(_DeleteButton);
var _ExportCSVButton = __webpack_require__(200);
var _ExportCSVButton2 = _interopRequireDefault(_ExportCSVButton);
var _ShowSelectedOnlyButton = __webpack_require__(201);
var _ShowSelectedOnlyButton2 = _interopRequireDefault(_ShowSelectedOnlyButton);
var _SearchField = __webpack_require__(202);
var _SearchField2 = _interopRequireDefault(_SearchField);
var _ClearSearchButton = __webpack_require__(203);
var _ClearSearchButton2 = _interopRequireDefault(_ClearSearchButton);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-console: 0 */
// import classSet from 'classnames';
// import editor from '../Editor';
var ToolBar = function (_Component) {
_inherits(ToolBar, _Component);
function ToolBar(props) {
var _arguments = arguments;
_classCallCheck(this, ToolBar);
var _this = _possibleConstructorReturn(this, (ToolBar.__proto__ || Object.getPrototypeOf(ToolBar)).call(this, props));
_this.handleSaveBtnClick = function () {
return _this.__handleSaveBtnClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleModalClose = function () {
return _this.__handleModalClose__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleModalOpen = function () {
return _this.__handleModalOpen__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleShowOnlyToggle = function () {
return _this.__handleShowOnlyToggle__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleDropRowBtnClick = function () {
return _this.__handleDropRowBtnClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleDebounce = function (func, wait, immediate) {
var timeout = void 0;
return function () {
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(_this, _arguments);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 0);
if (callNow) {
func.appy(_this, _arguments);
}
};
};
_this.handleKeyUp = function () {
return _this.__handleKeyUp__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleExportCSV = function () {
return _this.__handleExportCSV__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleClearBtnClick = function () {
return _this.__handleClearBtnClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.timeouteClear = 0;
_this.modalClassName;
_this.state = {
isInsertModalOpen: false,
validateState: null,
shakeEditor: false,
showSelected: false
};
return _this;
}
_createClass(ToolBar, [{
key: 'componentWillMount',
value: function componentWillMount() {
var _this2 = this;
var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0;
this.debounceCallback = this.handleDebounce(function () {
var seachInput = _this2.refs.seachInput;
seachInput && _this2.props.onSearch(seachInput.getValue());
}, delay);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.reset) {
this.setSearchInput('');
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'setSearchInput',
value: function setSearchInput(text) {
var seachInput = this.refs.seachInput;
if (seachInput && seachInput.value !== text) {
seachInput.value = text;
}
}
}, {
key: 'clearTimeout',
value: function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
}(function () {
if (this.timeouteClear) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'validateNewRow',
value: function validateNewRow(newRow) {
var _this3 = this;
var validateState = {};
var isValid = true;
var tempMsg = void 0;
var responseType = void 0;
this.props.columns.forEach(function (column) {
if (column.editable && column.editable.validator) {
// process validate
tempMsg = column.editable.validator(newRow[column.field]);
responseType = typeof tempMsg === 'undefined' ? 'undefined' : _typeof(tempMsg);
if (responseType !== 'object' && tempMsg !== true) {
_this3.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel');
isValid = false;
validateState[column.field] = tempMsg;
} else if (responseType === 'object' && tempMsg.isValid !== true) {
_this3.refs.notifier.notice(tempMsg.notification.type, tempMsg.notification.msg, tempMsg.notification.title);
isValid = false;
validateState[column.field] = tempMsg.notification.msg;
}
}
});
if (isValid) {
return true;
} else {
this.clearTimeout();
// show error in form and shake it
this.setState({ validateState: validateState, shakeEditor: true });
this.timeouteClear = setTimeout(function () {
_this3.setState({ shakeEditor: false });
}, 300);
return null;
}
}
}, {
key: '__handleSaveBtnClick__REACT_HOT_LOADER__',
value: function __handleSaveBtnClick__REACT_HOT_LOADER__(newRow) {
var _this4 = this;
if (!this.validateNewRow(newRow)) {
// validation fail
return;
}
var msg = this.props.onAddRow(newRow);
if (msg) {
this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel');
this.clearTimeout();
// shake form and hack prevent modal hide
this.setState({
shakeEditor: true,
validateState: 'this is hack for prevent bootstrap modal hide'
});
// clear animate class
this.timeouteClear = setTimeout(function () {
_this4.setState({ shakeEditor: false });
}, 300);
} else {
// reset state and hide modal hide
this.setState({
validateState: null,
shakeEditor: false,
isInsertModalOpen: false
});
}
}
}, {
key: '__handleModalClose__REACT_HOT_LOADER__',
value: function __handleModalClose__REACT_HOT_LOADER__() {
this.setState({ isInsertModalOpen: false });
}
}, {
key: '__handleModalOpen__REACT_HOT_LOADER__',
value: function __handleModalOpen__REACT_HOT_LOADER__() {
this.setState({ isInsertModalOpen: true });
}
}, {
key: '__handleShowOnlyToggle__REACT_HOT_LOADER__',
value: function __handleShowOnlyToggle__REACT_HOT_LOADER__() {
this.setState({
showSelected: !this.state.showSelected
});
this.props.onShowOnlySelected();
}
}, {
key: '__handleDropRowBtnClick__REACT_HOT_LOADER__',
value: function __handleDropRowBtnClick__REACT_HOT_LOADER__() {
this.props.onDropRow();
}
}, {
key: 'handleCloseBtn',
value: function handleCloseBtn() {
this.refs.warning.style.display = 'none';
}
}, {
key: '__handleKeyUp__REACT_HOT_LOADER__',
value: function __handleKeyUp__REACT_HOT_LOADER__(event) {
event.persist();
this.debounceCallback(event);
}
}, {
key: '__handleExportCSV__REACT_HOT_LOADER__',
value: function __handleExportCSV__REACT_HOT_LOADER__() {
this.props.onExportCSV();
}
}, {
key: '__handleClearBtnClick__REACT_HOT_LOADER__',
value: function __handleClearBtnClick__REACT_HOT_LOADER__() {
var seachInput = this.refs.seachInput;
seachInput && seachInput.setValue('');
this.props.onSearch('');
}
}, {
key: 'render',
value: function render() {
this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++;
var toolbar = null;
var btnGroup = null;
var insertBtn = null;
var deleteBtn = null;
var exportCSVBtn = null;
var showSelectedOnlyBtn = null;
if (this.props.enableInsert) {
if (this.props.insertBtn) {
insertBtn = this.renderCustomBtn(this.props.insertBtn, [this.handleModalOpen], _InsertButton2.default.name, 'onClick', this.handleModalOpen);
} else {
insertBtn = _react2.default.createElement(_InsertButton2.default, { btnText: this.props.insertText,
onClick: this.handleModalOpen });
}
}
if (this.props.enableDelete) {
if (this.props.deleteBtn) {
deleteBtn = this.renderCustomBtn(this.props.deleteBtn, [this.handleDropRowBtnClick], _DeleteButton2.default.name, 'onClick', this.handleDropRowBtnClick);
} else {
deleteBtn = _react2.default.createElement(_DeleteButton2.default, { btnText: this.props.deleteText,
onClick: this.handleDropRowBtnClick });
}
}
if (this.props.enableShowOnlySelected) {
if (this.props.showSelectedOnlyBtn) {
showSelectedOnlyBtn = this.renderCustomBtn(this.props.showSelectedOnlyBtn, [this.handleShowOnlyToggle, this.state.showSelected], _ShowSelectedOnlyButton2.default.name, 'onClick', this.handleShowOnlyToggle);
} else {
showSelectedOnlyBtn = _react2.default.createElement(_ShowSelectedOnlyButton2.default, { toggle: this.state.showSelected,
onClick: this.handleShowOnlyToggle });
}
}
if (this.props.enableExportCSV) {
if (this.props.exportCSVBtn) {
exportCSVBtn = this.renderCustomBtn(this.props.exportCSVBtn, [this.handleExportCSV], _ExportCSVButton2.default.name, 'onClick', this.handleExportCSV);
} else {
exportCSVBtn = _react2.default.createElement(_ExportCSVButton2.default, { btnText: this.props.exportCSVText,
onClick: this.handleExportCSV });
}
}
if (this.props.btnGroup) {
btnGroup = this.props.btnGroup({
exportCSVBtn: exportCSVBtn,
insertBtn: insertBtn,
deleteBtn: deleteBtn,
showSelectedOnlyBtn: showSelectedOnlyBtn
});
} else {
btnGroup = _react2.default.createElement(
'div',
{ className: 'btn-group btn-group-sm', role: 'group' },
exportCSVBtn,
insertBtn,
deleteBtn,
showSelectedOnlyBtn
);
}
var _renderSearchPanel = this.renderSearchPanel(),
_renderSearchPanel2 = _slicedToArray(_renderSearchPanel, 3),
searchPanel = _renderSearchPanel2[0],
searchField = _renderSearchPanel2[1],
clearBtn = _renderSearchPanel2[2];
var modal = this.props.enableInsert ? this.renderInsertRowModal() : null;
if (this.props.toolBar) {
toolbar = this.props.toolBar({
components: {
exportCSVBtn: exportCSVBtn,
insertBtn: insertBtn,
deleteBtn: deleteBtn,
showSelectedOnlyBtn: showSelectedOnlyBtn,
searchPanel: searchPanel,
btnGroup: btnGroup,
searchField: searchField,
clearBtn: clearBtn
},
event: {
openInsertModal: this.handleModalOpen,
closeInsertModal: this.handleModalClose,
dropRow: this.handleDropRowBtnClick,
showOnlyToogle: this.handleShowOnlyToggle,
exportCSV: this.handleExportCSV,
search: this.props.onSearch
}
});
} else {
toolbar = _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'div',
{ className: 'col-xs-6 col-sm-6 col-md-6 col-lg-8' },
this.props.searchPosition === 'left' ? searchPanel : btnGroup
),
_react2.default.createElement(
'div',
{ className: 'col-xs-6 col-sm-6 col-md-6 col-lg-4' },
this.props.searchPosition === 'left' ? btnGroup : searchPanel
)
);
}
return _react2.default.createElement(
'div',
{ className: 'row' },
toolbar,
_react2.default.createElement(_Notification2.default, { ref: 'notifier' }),
modal
);
}
}, {
key: 'renderSearchPanel',
value: function renderSearchPanel() {
if (this.props.enableSearch) {
var classNames = 'form-group form-group-sm react-bs-table-search-form';
var clearBtn = null;
var searchField = null;
var searchPanel = null;
if (this.props.clearSearch) {
if (this.props.clearSearchBtn) {
clearBtn = this.renderCustomBtn(this.props.clearSearchBtn, [this.handleClearBtnClick], _ClearSearchButton2.default.name, 'onClick', this.handleClearBtnClick); /* eslint max-len: 0*/
} else {
clearBtn = _react2.default.createElement(_ClearSearchButton2.default, { onClick: this.handleClearBtnClick });
}
classNames += ' input-group input-group-sm';
}
if (this.props.searchField) {
searchField = this.props.searchField({
search: this.handleKeyUp,
defaultValue: this.props.defaultSearch,
placeholder: this.props.searchPlaceholder
});
if (searchField.type.name === _SearchField2.default.name) {
searchField = _react2.default.cloneElement(searchField, {
ref: 'seachInput',
onKeyUp: this.handleKeyUp
});
} else {
searchField = _react2.default.cloneElement(searchField, {
ref: 'seachInput'
});
}
} else {
searchField = _react2.default.createElement(_SearchField2.default, { ref: 'seachInput',
defaultValue: this.props.defaultSearch,
placeholder: this.props.searchPlaceholder,
onKeyUp: this.handleKeyUp });
}
if (this.props.searchPanel) {
searchPanel = this.props.searchPanel({
searchField: searchField, clearBtn: clearBtn,
search: this.props.onSearch,
defaultValue: this.props.defaultSearch,
placeholder: this.props.searchPlaceholder,
clearBtnClick: this.handleClearBtnClick
});
} else {
searchPanel = _react2.default.createElement(
'div',
{ className: classNames },
searchField,
_react2.default.createElement(
'span',
{ className: 'input-group-btn' },
clearBtn
)
);
}
return [searchPanel, searchField, clearBtn];
} else {
return [];
}
}
}, {
key: 'renderInsertRowModal',
value: function renderInsertRowModal() {
var validateState = this.state.validateState || {};
var _props = this.props,
columns = _props.columns,
ignoreEditable = _props.ignoreEditable,
insertModalHeader = _props.insertModalHeader,
insertModalBody = _props.insertModalBody,
insertModalFooter = _props.insertModalFooter,
insertModal = _props.insertModal;
var modal = void 0;
modal = insertModal && insertModal(this.handleModalClose, this.handleSaveBtnClick, columns, validateState, ignoreEditable);
if (!modal) {
modal = _react2.default.createElement(_InsertModal2.default, {
columns: columns,
validateState: validateState,
ignoreEditable: ignoreEditable,
onModalClose: this.handleModalClose,
onSave: this.handleSaveBtnClick,
headerComponent: insertModalHeader,
bodyComponent: insertModalBody,
footerComponent: insertModalFooter });
}
return _react2.default.createElement(
_reactModal2.default,
{ className: 'react-bs-insert-modal modal-dialog',
isOpen: this.state.isInsertModalOpen,
onRequestClose: this.handleModalClose,
contentLabel: 'Modal' },
modal
);
}
}, {
key: 'renderCustomBtn',
value: function renderCustomBtn(cb, params, componentName, eventName, event) {
var element = cb.apply(null, params);
if (element.type.name === componentName && !element.props[eventName]) {
var props = {};
props[eventName] = event;
element = _react2.default.cloneElement(element, props);
}
return element;
}
}]);
return ToolBar;
}(_react.Component);
ToolBar.modalSeq = 0;
ToolBar.propTypes = {
onAddRow: _react.PropTypes.func,
onDropRow: _react.PropTypes.func,
onShowOnlySelected: _react.PropTypes.func,
enableInsert: _react.PropTypes.bool,
enableDelete: _react.PropTypes.bool,
enableSearch: _react.PropTypes.bool,
enableShowOnlySelected: _react.PropTypes.bool,
columns: _react.PropTypes.array,
searchPlaceholder: _react.PropTypes.string,
exportCSVText: _react.PropTypes.string,
insertText: _react.PropTypes.string,
deleteText: _react.PropTypes.string,
saveText: _react.PropTypes.string,
closeText: _react.PropTypes.string,
clearSearch: _react.PropTypes.bool,
ignoreEditable: _react.PropTypes.bool,
defaultSearch: _react.PropTypes.string,
insertModalHeader: _react.PropTypes.func,
insertModalBody: _react.PropTypes.func,
insertModalFooter: _react.PropTypes.func,
insertModal: _react.PropTypes.func,
insertBtn: _react.PropTypes.func,
deleteBtn: _react.PropTypes.func,
showSelectedOnlyBtn: _react.PropTypes.func,
exportCSVBtn: _react.PropTypes.func,
clearSearchBtn: _react.PropTypes.func,
searchField: _react.PropTypes.func,
searchPanel: _react.PropTypes.func,
btnGroup: _react.PropTypes.func,
toolBar: _react.PropTypes.func,
searchPosition: _react.PropTypes.string,
reset: _react.PropTypes.bool
};
ToolBar.defaultProps = {
reset: false,
enableInsert: false,
enableDelete: false,
enableSearch: false,
enableShowOnlySelected: false,
clearSearch: false,
ignoreEditable: false,
exportCSVText: _Const2.default.EXPORT_CSV_TEXT,
insertText: _Const2.default.INSERT_BTN_TEXT,
deleteText: _Const2.default.DELETE_BTN_TEXT,
saveText: _Const2.default.SAVE_BTN_TEXT,
closeText: _Const2.default.CLOSE_BTN_TEXT
};
var _default = ToolBar;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(ToolBar, 'ToolBar', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ToolBar.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ToolBar.js');
}();
;
/***/ },
/* 184 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(185);
/***/ },
/* 185 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(6);
var ExecutionEnvironment = __webpack_require__(186);
var ModalPortal = React.createFactory(__webpack_require__(187));
var ariaAppHider = __webpack_require__(192);
var elementClass = __webpack_require__(193);
var renderSubtreeIntoContainer = __webpack_require__(6).unstable_renderSubtreeIntoContainer;
var Assign = __webpack_require__(191);
var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};
function getParentElement(parentSelector) {
return parentSelector();
}
var Modal = React.createClass({
displayName: 'Modal',
statics: {
setAppElement: function(element) {
AppElement = ariaAppHider.setElement(element);
},
injectCSS: function() {
"production" !== process.env.NODE_ENV
&& console.warn('React-Modal: injectCSS has been deprecated ' +
'and no longer has any effect. It will be removed in a later version');
}
},
propTypes: {
isOpen: React.PropTypes.bool.isRequired,
style: React.PropTypes.shape({
content: React.PropTypes.object,
overlay: React.PropTypes.object
}),
portalClassName: React.PropTypes.string,
appElement: React.PropTypes.instanceOf(SafeHTMLElement),
onAfterOpen: React.PropTypes.func,
onRequestClose: React.PropTypes.func,
closeTimeoutMS: React.PropTypes.number,
ariaHideApp: React.PropTypes.bool,
shouldCloseOnOverlayClick: React.PropTypes.bool,
parentSelector: React.PropTypes.func,
role: React.PropTypes.string,
contentLabel: React.PropTypes.string.isRequired
},
getDefaultProps: function () {
return {
isOpen: false,
portalClassName: 'ReactModalPortal',
ariaHideApp: true,
closeTimeoutMS: 0,
shouldCloseOnOverlayClick: true,
parentSelector: function () { return document.body; }
};
},
componentDidMount: function() {
this.node = document.createElement('div');
this.node.className = this.props.portalClassName;
var parent = getParentElement(this.props.parentSelector);
parent.appendChild(this.node);
this.renderPortal(this.props);
},
componentWillReceiveProps: function(newProps) {
var currentParent = getParentElement(this.props.parentSelector);
var newParent = getParentElement(newProps.parentSelector);
if(newParent !== currentParent) {
currentParent.removeChild(this.node);
newParent.appendChild(this.node);
}
this.renderPortal(newProps);
},
componentWillUnmount: function() {
if (this.props.ariaHideApp) {
ariaAppHider.show(this.props.appElement);
}
ReactDOM.unmountComponentAtNode(this.node);
var parent = getParentElement(this.props.parentSelector);
parent.removeChild(this.node);
elementClass(document.body).remove('ReactModal__Body--open');
},
renderPortal: function(props) {
if (props.isOpen) {
elementClass(document.body).add('ReactModal__Body--open');
} else {
elementClass(document.body).remove('ReactModal__Body--open');
}
if (props.ariaHideApp) {
ariaAppHider.toggle(props.isOpen, props.appElement);
}
this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
},
render: function () {
return React.DOM.noscript();
}
});
Modal.defaultStyles = {
overlay: {
position : 'fixed',
top : 0,
left : 0,
right : 0,
bottom : 0,
backgroundColor : 'rgba(255, 255, 255, 0.75)'
},
content: {
position : 'absolute',
top : '40px',
left : '40px',
right : '40px',
bottom : '40px',
border : '1px solid #ccc',
background : '#fff',
overflow : 'auto',
WebkitOverflowScrolling : 'touch',
borderRadius : '4px',
outline : 'none',
padding : '20px'
}
}
module.exports = Modal
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(167)))
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Based on code that is Copyright 2013-2015, Facebook, Inc.
All rights reserved.
*/
(function () {
'use strict';
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners:
canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen
};
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return ExecutionEnvironment;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = ExecutionEnvironment;
} else {
window.ExecutionEnvironment = ExecutionEnvironment;
}
}());
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
var React = __webpack_require__(2);
var div = React.DOM.div;
var focusManager = __webpack_require__(188);
var scopeTab = __webpack_require__(190);
var Assign = __webpack_require__(191);
// so that our CSS is statically analyzable
var CLASS_NAMES = {
overlay: {
base: 'ReactModal__Overlay',
afterOpen: 'ReactModal__Overlay--after-open',
beforeClose: 'ReactModal__Overlay--before-close'
},
content: {
base: 'ReactModal__Content',
afterOpen: 'ReactModal__Content--after-open',
beforeClose: 'ReactModal__Content--before-close'
}
};
var ModalPortal = module.exports = React.createClass({
displayName: 'ModalPortal',
shouldClose: null,
getDefaultProps: function() {
return {
style: {
overlay: {},
content: {}
}
};
},
getInitialState: function() {
return {
afterOpen: false,
beforeClose: false
};
},
componentDidMount: function() {
// Focus needs to be set when mounting and already open
if (this.props.isOpen) {
this.setFocusAfterRender(true);
this.open();
}
},
componentWillUnmount: function() {
clearTimeout(this.closeTimer);
},
componentWillReceiveProps: function(newProps) {
// Focus only needs to be set once when the modal is being opened
if (!this.props.isOpen && newProps.isOpen) {
this.setFocusAfterRender(true);
this.open();
} else if (this.props.isOpen && !newProps.isOpen) {
this.close();
}
},
componentDidUpdate: function () {
if (this.focusAfterRender) {
this.focusContent();
this.setFocusAfterRender(false);
}
},
setFocusAfterRender: function (focus) {
this.focusAfterRender = focus;
},
open: function() {
if (this.state.afterOpen && this.state.beforeClose) {
clearTimeout(this.closeTimer);
this.setState({ beforeClose: false });
} else {
focusManager.setupScopedFocus(this.node);
focusManager.markForFocusLater();
this.setState({isOpen: true}, function() {
this.setState({afterOpen: true});
if (this.props.isOpen && this.props.onAfterOpen) {
this.props.onAfterOpen();
}
}.bind(this));
}
},
close: function() {
if (!this.ownerHandlesClose())
return;
if (this.props.closeTimeoutMS > 0)
this.closeWithTimeout();
else
this.closeWithoutTimeout();
},
focusContent: function() {
// Don't steal focus from inner elements
if (!this.contentHasFocus()) {
this.refs.content.focus();
}
},
closeWithTimeout: function() {
this.setState({beforeClose: true}, function() {
this.closeTimer = setTimeout(this.closeWithoutTimeout, this.props.closeTimeoutMS);
}.bind(this));
},
closeWithoutTimeout: function() {
this.setState({
beforeClose: false,
isOpen: false,
afterOpen: false,
}, this.afterClose);
},
afterClose: function() {
focusManager.returnFocus();
focusManager.teardownScopedFocus();
},
handleKeyDown: function(event) {
if (event.keyCode == 9 /*tab*/) scopeTab(this.refs.content, event);
if (event.keyCode == 27 /*esc*/) {
event.preventDefault();
this.requestClose(event);
}
},
handleOverlayMouseDown: function(event) {
if (this.shouldClose === null) {
this.shouldClose = true;
}
},
handleOverlayMouseUp: function(event) {
if (this.shouldClose && this.props.shouldCloseOnOverlayClick) {
if (this.ownerHandlesClose())
this.requestClose(event);
else
this.focusContent();
}
this.shouldClose = null;
},
handleContentMouseDown: function(event) {
this.shouldClose = false;
},
handleContentMouseUp: function(event) {
this.shouldClose = false;
},
requestClose: function(event) {
if (this.ownerHandlesClose())
this.props.onRequestClose(event);
},
ownerHandlesClose: function() {
return this.props.onRequestClose;
},
shouldBeClosed: function() {
return !this.props.isOpen && !this.state.beforeClose;
},
contentHasFocus: function() {
return document.activeElement === this.refs.content || this.refs.content.contains(document.activeElement);
},
buildClassName: function(which, additional) {
var className = CLASS_NAMES[which].base;
if (this.state.afterOpen)
className += ' '+CLASS_NAMES[which].afterOpen;
if (this.state.beforeClose)
className += ' '+CLASS_NAMES[which].beforeClose;
return additional ? className + ' ' + additional : className;
},
render: function() {
var contentStyles = (this.props.className) ? {} : this.props.defaultStyles.content;
var overlayStyles = (this.props.overlayClassName) ? {} : this.props.defaultStyles.overlay;
return this.shouldBeClosed() ? div() : (
div({
ref: "overlay",
className: this.buildClassName('overlay', this.props.overlayClassName),
style: Assign({}, overlayStyles, this.props.style.overlay || {}),
onMouseDown: this.handleOverlayMouseDown,
onMouseUp: this.handleOverlayMouseUp
},
div({
ref: "content",
style: Assign({}, contentStyles, this.props.style.content || {}),
className: this.buildClassName('content', this.props.className),
tabIndex: "-1",
onKeyDown: this.handleKeyDown,
onMouseDown: this.handleContentMouseDown,
onMouseUp: this.handleContentMouseUp,
role: this.props.role,
"aria-label": this.props.contentLabel
},
this.props.children
)
)
);
}
});
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
var findTabbable = __webpack_require__(189);
var modalElement = null;
var focusLaterElement = null;
var needToFocus = false;
function handleBlur(event) {
needToFocus = true;
}
function handleFocus(event) {
if (needToFocus) {
needToFocus = false;
if (!modalElement) {
return;
}
// need to see how jQuery shims document.on('focusin') so we don't need the
// setTimeout, firefox doesn't support focusin, if it did, we could focus
// the element outside of a setTimeout. Side-effect of this implementation
// is that the document.body gets focus, and then we focus our element right
// after, seems fine.
setTimeout(function() {
if (modalElement.contains(document.activeElement))
return;
var el = (findTabbable(modalElement)[0] || modalElement);
el.focus();
}, 0);
}
}
exports.markForFocusLater = function() {
focusLaterElement = document.activeElement;
};
exports.returnFocus = function() {
try {
focusLaterElement.focus();
}
catch (e) {
console.warn('You tried to return focus to '+focusLaterElement+' but it is not in the DOM anymore');
}
focusLaterElement = null;
};
exports.setupScopedFocus = function(element) {
modalElement = element;
if (window.addEventListener) {
window.addEventListener('blur', handleBlur, false);
document.addEventListener('focus', handleFocus, true);
} else {
window.attachEvent('onBlur', handleBlur);
document.attachEvent('onFocus', handleFocus);
}
};
exports.teardownScopedFocus = function() {
modalElement = null;
if (window.addEventListener) {
window.removeEventListener('blur', handleBlur);
document.removeEventListener('focus', handleFocus);
} else {
window.detachEvent('onBlur', handleBlur);
document.detachEvent('onFocus', handleFocus);
}
};
/***/ },
/* 189 */
/***/ function(module, exports) {
/*!
* Adapted from jQuery UI core
*
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
function focusable(element, isTabIndexNotNaN) {
var nodeName = element.nodeName.toLowerCase();
return (/input|select|textarea|button|object/.test(nodeName) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) && visible(element);
}
function hidden(el) {
return (el.offsetWidth <= 0 && el.offsetHeight <= 0) ||
el.style.display === 'none';
}
function visible(element) {
while (element) {
if (element === document.body) break;
if (hidden(element)) return false;
element = element.parentNode;
}
return true;
}
function tabbable(element) {
var tabIndex = element.getAttribute('tabindex');
if (tabIndex === null) tabIndex = undefined;
var isTabIndexNaN = isNaN(tabIndex);
return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
}
function findTabbableDescendants(element) {
return [].slice.call(element.querySelectorAll('*'), 0).filter(function(el) {
return tabbable(el);
});
}
module.exports = findTabbableDescendants;
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
var findTabbable = __webpack_require__(189);
module.exports = function(node, event) {
var tabbable = findTabbable(node);
if (!tabbable.length) {
event.preventDefault();
return;
}
var finalTabbable = tabbable[event.shiftKey ? 0 : tabbable.length - 1];
var leavingFinalTabbable = (
finalTabbable === document.activeElement ||
// handle immediate shift+tab after opening with mouse
node === document.activeElement
);
if (!leavingFinalTabbable) return;
event.preventDefault();
var target = tabbable[event.shiftKey ? tabbable.length - 1 : 0];
target.focus();
};
/***/ },
/* 191 */
/***/ function(module, exports) {
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]';
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/** Used for built-in 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/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max;
/** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = (isArray(value) || isArguments(value))
? baseTimes(value.length, String)
: [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
object[key] = value;
}
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
};
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
assignValue(object, key, newValue === undefined ? source[key] : newValue);
}
return object;
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = assign;
/***/ },
/* 192 */
/***/ function(module, exports) {
var _element = typeof document !== 'undefined' ? document.body : null;
function setElement(element) {
if (typeof element === 'string') {
var el = document.querySelectorAll(element);
element = 'length' in el ? el[0] : el;
}
_element = element || _element;
return _element;
}
function hide(appElement) {
validateElement(appElement);
(appElement || _element).setAttribute('aria-hidden', 'true');
}
function show(appElement) {
validateElement(appElement);
(appElement || _element).removeAttribute('aria-hidden');
}
function toggle(shouldHide, appElement) {
if (shouldHide)
hide(appElement);
else
show(appElement);
}
function validateElement(appElement) {
if (!appElement && !_element)
throw new Error('react-modal: You must set an element with `Modal.setAppElement(el)` to make this accessible');
}
function resetForTesting() {
_element = document.body;
}
exports.toggle = toggle;
exports.setElement = setElement;
exports.show = show;
exports.hide = hide;
exports.resetForTesting = resetForTesting;
/***/ },
/* 193 */
/***/ function(module, exports) {
module.exports = function(opts) {
return new ElementClass(opts)
}
function indexOf(arr, prop) {
if (arr.indexOf) return arr.indexOf(prop)
for (var i = 0, len = arr.length; i < len; i++)
if (arr[i] === prop) return i
return -1
}
function ElementClass(opts) {
if (!(this instanceof ElementClass)) return new ElementClass(opts)
var self = this
if (!opts) opts = {}
// similar doing instanceof HTMLElement but works in IE8
if (opts.nodeType) opts = {el: opts}
this.opts = opts
this.el = opts.el || document.body
if (typeof this.el !== 'object') this.el = document.querySelector(this.el)
}
ElementClass.prototype.add = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return el.className = className
var classes = el.className.split(' ')
if (indexOf(classes, className) > -1) return classes
classes.push(className)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.remove = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return
var classes = el.className.split(' ')
var idx = indexOf(classes, className)
if (idx > -1) classes.splice(idx, 1)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.has = function(className) {
var el = this.el
if (!el) return
var classes = el.className.split(' ')
return indexOf(classes, className) > -1
}
ElementClass.prototype.toggle = function(className) {
var el = this.el
if (!el) return
if (this.has(className)) this.remove(className)
else this.add(className)
}
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _InsertModalHeader = __webpack_require__(195);
var _InsertModalHeader2 = _interopRequireDefault(_InsertModalHeader);
var _InsertModalFooter = __webpack_require__(196);
var _InsertModalFooter2 = _interopRequireDefault(_InsertModalFooter);
var _InsertModalBody = __webpack_require__(197);
var _InsertModalBody2 = _interopRequireDefault(_InsertModalBody);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint no-console: 0 */
var defaultModalClassName = 'react-bs-table-insert-modal';
var InsertModal = function (_Component) {
_inherits(InsertModal, _Component);
function InsertModal() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, InsertModal);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = InsertModal.__proto__ || Object.getPrototypeOf(InsertModal)).call.apply(_ref, [this].concat(args))), _this), _this.handleSave = function () {
var _this2;
return (_this2 = _this).__handleSave__REACT_HOT_LOADER__.apply(_this2, arguments);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(InsertModal, [{
key: '__handleSave__REACT_HOT_LOADER__',
value: function __handleSave__REACT_HOT_LOADER__() {
var bodyRefs = this.refs.body;
if (bodyRefs.getFieldValue) {
this.props.onSave(bodyRefs.getFieldValue());
} else {
console.error('Custom InsertModalBody should implement getFieldValue function\n and should return an object presented as the new row that user input.');
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
headerComponent = _props.headerComponent,
footerComponent = _props.footerComponent,
bodyComponent = _props.bodyComponent;
var _props2 = this.props,
columns = _props2.columns,
validateState = _props2.validateState,
ignoreEditable = _props2.ignoreEditable,
onModalClose = _props2.onModalClose;
var bodyAttr = { columns: columns, validateState: validateState, ignoreEditable: ignoreEditable };
bodyComponent = bodyComponent && bodyComponent(columns, validateState, ignoreEditable);
headerComponent = headerComponent && headerComponent(onModalClose, this.handleSave);
footerComponent = footerComponent && footerComponent(onModalClose, this.handleSave);
if (bodyComponent) {
bodyComponent = _react2.default.cloneElement(bodyComponent, { ref: 'body' });
}
if (headerComponent && headerComponent.type.name === _InsertModalHeader2.default.name) {
var eventProps = {};
if (!headerComponent.props.onModalClose) eventProps.onModalClose = onModalClose;
if (!headerComponent.props.onSave) eventProps.onSave = this.handleSave;
if (Object.keys(eventProps).length > 0) {
headerComponent = _react2.default.cloneElement(headerComponent, eventProps);
}
} else if (headerComponent && headerComponent.type.name !== _InsertModalHeader2.default.name) {
var className = headerComponent.props.className;
if (typeof className === 'undefined' || className.indexOf('modal-header') === -1) {
headerComponent = _react2.default.createElement(
'div',
{ className: 'modal-header' },
headerComponent
);
}
}
if (footerComponent && footerComponent.type.name === _InsertModalFooter2.default.name) {
var _eventProps = {};
if (!footerComponent.props.onModalClose) _eventProps.onModalClose = onModalClose;
if (!footerComponent.props.onSave) _eventProps.onSave = this.handleSave;
if (Object.keys(_eventProps).length > 0) {
footerComponent = _react2.default.cloneElement(footerComponent, _eventProps);
}
} else if (footerComponent && footerComponent.type.name !== _InsertModalFooter2.default.name) {
var _className = footerComponent.props.className;
if (typeof _className === 'undefined' || _className.indexOf('modal-footer') === -1) {
footerComponent = _react2.default.createElement(
'div',
{ className: 'modal-footer' },
footerComponent
);
}
}
return _react2.default.createElement(
'div',
{ className: 'modal-content ' + defaultModalClassName },
headerComponent || _react2.default.createElement(_InsertModalHeader2.default, {
className: 'react-bs-table-inser-modal-header',
onModalClose: onModalClose }),
bodyComponent || _react2.default.createElement(_InsertModalBody2.default, _extends({ ref: 'body' }, bodyAttr)),
footerComponent || _react2.default.createElement(_InsertModalFooter2.default, {
className: 'react-bs-table-inser-modal-footer',
onModalClose: onModalClose,
onSave: this.handleSave })
);
}
}]);
return InsertModal;
}(_react.Component);
var _default = InsertModal;
exports.default = _default;
InsertModal.propTypes = {
columns: _react.PropTypes.array.isRequired,
validateState: _react.PropTypes.object.isRequired,
ignoreEditable: _react.PropTypes.bool,
headerComponent: _react.PropTypes.func,
bodyComponent: _react.PropTypes.func,
footerComponent: _react.PropTypes.func,
onModalClose: _react.PropTypes.func,
onSave: _react.PropTypes.func
};
InsertModal.defaultProps = {};
;
var _temp2 = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(defaultModalClassName, 'defaultModalClassName', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModal.js');
__REACT_HOT_LOADER__.register(InsertModal, 'InsertModal', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModal.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModal.js');
}();
;
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InsertModalHeader = function (_Component) {
_inherits(InsertModalHeader, _Component);
function InsertModalHeader() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, InsertModalHeader);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = InsertModalHeader.__proto__ || Object.getPrototypeOf(InsertModalHeader)).call.apply(_ref, [this].concat(args))), _this), _this.handleCloseBtnClick = function () {
var _this2;
return (_this2 = _this).__handleCloseBtnClick__REACT_HOT_LOADER__.apply(_this2, arguments);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(InsertModalHeader, [{
key: '__handleCloseBtnClick__REACT_HOT_LOADER__',
value: function __handleCloseBtnClick__REACT_HOT_LOADER__(e) {
var _props = this.props,
onModalClose = _props.onModalClose,
beforeClose = _props.beforeClose;
beforeClose && beforeClose(e);
onModalClose();
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
title = _props2.title,
hideClose = _props2.hideClose,
className = _props2.className,
children = _props2.children;
var closeBtn = hideClose ? null : _react2.default.createElement(
'button',
{ type: 'button',
className: 'close', onClick: this.handleCloseBtnClick },
_react2.default.createElement(
'span',
{ 'aria-hidden': 'true' },
'\xD7'
),
_react2.default.createElement(
'span',
{ className: 'sr-only' },
'Close'
)
);
var content = children || _react2.default.createElement(
'span',
null,
closeBtn,
_react2.default.createElement(
'h4',
{ className: 'modal-title' },
title
)
);
return _react2.default.createElement(
'div',
{ className: 'modal-header ' + className },
content
);
}
}]);
return InsertModalHeader;
}(_react.Component);
InsertModalHeader.propTypes = {
className: _react.PropTypes.string,
title: _react.PropTypes.string,
onModalClose: _react.PropTypes.func,
hideClose: _react.PropTypes.bool,
beforeClose: _react.PropTypes.func
};
InsertModalHeader.defaultProps = {
className: '',
title: 'Add Row',
onModalClose: undefined,
hideClose: false,
beforeClose: undefined
};
var _default = InsertModalHeader;
exports.default = _default;
;
var _temp2 = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(InsertModalHeader, 'InsertModalHeader', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalHeader.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalHeader.js');
}();
;
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InsertModalFooter = function (_Component) {
_inherits(InsertModalFooter, _Component);
function InsertModalFooter() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, InsertModalFooter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = InsertModalFooter.__proto__ || Object.getPrototypeOf(InsertModalFooter)).call.apply(_ref, [this].concat(args))), _this), _this.handleCloseBtnClick = function () {
var _this2;
return (_this2 = _this).__handleCloseBtnClick__REACT_HOT_LOADER__.apply(_this2, arguments);
}, _this.handleSaveBtnClick = function () {
var _this3;
return (_this3 = _this).__handleSaveBtnClick__REACT_HOT_LOADER__.apply(_this3, arguments);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(InsertModalFooter, [{
key: '__handleCloseBtnClick__REACT_HOT_LOADER__',
value: function __handleCloseBtnClick__REACT_HOT_LOADER__(e) {
var _props = this.props,
beforeClose = _props.beforeClose,
onModalClose = _props.onModalClose;
beforeClose && beforeClose(e);
onModalClose();
}
}, {
key: '__handleSaveBtnClick__REACT_HOT_LOADER__',
value: function __handleSaveBtnClick__REACT_HOT_LOADER__(e) {
var _props2 = this.props,
beforeSave = _props2.beforeSave,
onSave = _props2.onSave;
beforeSave && beforeSave(e);
onSave();
}
}, {
key: 'render',
value: function render() {
var _props3 = this.props,
className = _props3.className,
saveBtnText = _props3.saveBtnText,
closeBtnText = _props3.closeBtnText,
closeBtnContextual = _props3.closeBtnContextual,
saveBtnContextual = _props3.saveBtnContextual,
closeBtnClass = _props3.closeBtnClass,
saveBtnClass = _props3.saveBtnClass,
children = _props3.children;
var content = children || _react2.default.createElement(
'span',
null,
_react2.default.createElement(
'button',
{
type: 'button',
className: 'btn ' + closeBtnContextual + ' ' + closeBtnClass,
onClick: this.handleCloseBtnClick },
closeBtnText
),
_react2.default.createElement(
'button',
{
type: 'button',
className: 'btn ' + saveBtnContextual + ' ' + saveBtnClass,
onClick: this.handleSaveBtnClick },
saveBtnText
)
);
return _react2.default.createElement(
'div',
{ className: 'modal-footer ' + className },
content
);
}
}]);
return InsertModalFooter;
}(_react.Component);
InsertModalFooter.propTypes = {
className: _react.PropTypes.string,
saveBtnText: _react.PropTypes.string,
closeBtnText: _react.PropTypes.string,
closeBtnContextual: _react.PropTypes.string,
saveBtnContextual: _react.PropTypes.string,
closeBtnClass: _react.PropTypes.string,
saveBtnClass: _react.PropTypes.string,
beforeClose: _react.PropTypes.func,
beforeSave: _react.PropTypes.func,
onSave: _react.PropTypes.func,
onModalClose: _react.PropTypes.func
};
InsertModalFooter.defaultProps = {
className: '',
saveBtnText: _Const2.default.SAVE_BTN_TEXT,
closeBtnText: _Const2.default.CLOSE_BTN_TEXT,
closeBtnContextual: 'btn-default',
saveBtnContextual: 'btn-primary',
closeBtnClass: '',
saveBtnClass: '',
beforeClose: undefined,
beforeSave: undefined
};
var _default = InsertModalFooter;
exports.default = _default;
;
var _temp2 = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(InsertModalFooter, 'InsertModalFooter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalFooter.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalFooter.js');
}();
;
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Editor = __webpack_require__(13);
var _Editor2 = _interopRequireDefault(_Editor);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint react/display-name: 0 */
var InsertModalBody = function (_Component) {
_inherits(InsertModalBody, _Component);
function InsertModalBody() {
_classCallCheck(this, InsertModalBody);
return _possibleConstructorReturn(this, (InsertModalBody.__proto__ || Object.getPrototypeOf(InsertModalBody)).apply(this, arguments));
}
_createClass(InsertModalBody, [{
key: 'getFieldValue',
value: function getFieldValue() {
var _this2 = this;
var newRow = {};
this.props.columns.forEach(function (column, i) {
var inputVal = void 0;
if (column.autoValue) {
// when you want same auto generate value and not allow edit, example ID field
var time = new Date().getTime();
inputVal = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time;
} else if (column.hiddenOnInsert || !column.field) {
inputVal = '';
} else {
var dom = _this2.refs[column.field + i];
inputVal = dom.value;
if (column.editable && column.editable.type === 'checkbox') {
var values = inputVal.split(':');
inputVal = dom.checked ? values[0] : values[1];
}
}
newRow[column.field] = inputVal;
}, this);
return newRow;
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
columns = _props.columns,
validateState = _props.validateState,
ignoreEditable = _props.ignoreEditable;
return _react2.default.createElement(
'div',
{ className: 'modal-body' },
columns.map(function (column, i) {
var editable = column.editable,
format = column.format,
field = column.field,
name = column.name,
autoValue = column.autoValue,
hiddenOnInsert = column.hiddenOnInsert;
var attr = {
ref: field + i,
placeholder: editable.placeholder ? editable.placeholder : name
};
if (autoValue || hiddenOnInsert || !column.field) {
// when you want same auto generate value
// and not allow edit, for example ID field
return null;
}
var error = validateState[field] ? _react2.default.createElement(
'span',
{ className: 'help-block bg-danger' },
validateState[field]
) : null;
return _react2.default.createElement(
'div',
{ className: 'form-group', key: field },
_react2.default.createElement(
'label',
null,
name
),
(0, _Editor2.default)(editable, attr, format, '', undefined, ignoreEditable),
error
);
})
);
}
}]);
return InsertModalBody;
}(_react.Component);
InsertModalBody.propTypes = {
columns: _react.PropTypes.array,
validateState: _react.PropTypes.object,
ignoreEditable: _react.PropTypes.bool
};
InsertModalBody.defaultProps = {
validateState: {},
ignoreEditable: false
};
var _default = InsertModalBody;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(InsertModalBody, 'InsertModalBody', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalBody.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertModalBody.js');
}();
;
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var insertBtnDefaultClass = 'react-bs-table-add-btn';
var InsertButton = function (_Component) {
_inherits(InsertButton, _Component);
function InsertButton() {
_classCallCheck(this, InsertButton);
return _possibleConstructorReturn(this, (InsertButton.__proto__ || Object.getPrototypeOf(InsertButton)).apply(this, arguments));
}
_createClass(InsertButton, [{
key: 'render',
value: function render() {
var _props = this.props,
btnContextual = _props.btnContextual,
className = _props.className,
onClick = _props.onClick,
btnGlyphicon = _props.btnGlyphicon,
btnText = _props.btnText,
children = _props.children,
rest = _objectWithoutProperties(_props, ['btnContextual', 'className', 'onClick', 'btnGlyphicon', 'btnText', 'children']);
var content = children || _react2.default.createElement(
'span',
null,
_react2.default.createElement('i', { className: 'glyphicon ' + btnGlyphicon }),
btnText
);
return _react2.default.createElement(
'button',
_extends({ type: 'button',
className: 'btn ' + btnContextual + ' ' + insertBtnDefaultClass + ' ' + className,
onClick: onClick
}, rest),
content
);
}
}]);
return InsertButton;
}(_react.Component);
InsertButton.propTypes = {
btnText: _react.PropTypes.string,
btnContextual: _react.PropTypes.string,
className: _react.PropTypes.string,
onClick: _react.PropTypes.func,
btnGlyphicon: _react.PropTypes.string
};
InsertButton.defaultProps = {
btnText: _Const2.default.INSERT_BTN_TEXT,
btnContextual: 'btn-info',
className: '',
onClick: undefined,
btnGlyphicon: 'glyphicon-plus'
};
var _default = InsertButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(insertBtnDefaultClass, 'insertBtnDefaultClass', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertButton.js');
__REACT_HOT_LOADER__.register(InsertButton, 'InsertButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/InsertButton.js');
}();
;
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var deleteBtnDefaultClass = 'react-bs-table-del-btn';
var DeleteButton = function (_Component) {
_inherits(DeleteButton, _Component);
function DeleteButton() {
_classCallCheck(this, DeleteButton);
return _possibleConstructorReturn(this, (DeleteButton.__proto__ || Object.getPrototypeOf(DeleteButton)).apply(this, arguments));
}
_createClass(DeleteButton, [{
key: 'render',
value: function render() {
var _props = this.props,
btnContextual = _props.btnContextual,
className = _props.className,
onClick = _props.onClick,
btnGlyphicon = _props.btnGlyphicon,
btnText = _props.btnText,
children = _props.children,
rest = _objectWithoutProperties(_props, ['btnContextual', 'className', 'onClick', 'btnGlyphicon', 'btnText', 'children']);
var content = children || _react2.default.createElement(
'span',
null,
_react2.default.createElement('i', { className: 'glyphicon ' + btnGlyphicon }),
' ',
btnText
);
return _react2.default.createElement(
'button',
_extends({ type: 'button',
className: 'btn ' + btnContextual + ' ' + deleteBtnDefaultClass + ' ' + className,
onClick: onClick
}, rest),
content
);
}
}]);
return DeleteButton;
}(_react.Component);
DeleteButton.propTypes = {
btnText: _react.PropTypes.string,
btnContextual: _react.PropTypes.string,
className: _react.PropTypes.string,
onClick: _react.PropTypes.func,
btnGlyphicon: _react.PropTypes.string
};
DeleteButton.defaultProps = {
btnText: _Const2.default.DELETE_BTN_TEXT,
btnContextual: 'btn-warning',
className: '',
onClick: undefined,
btnGlyphicon: 'glyphicon-trash'
};
var _default = DeleteButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(deleteBtnDefaultClass, 'deleteBtnDefaultClass', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/DeleteButton.js');
__REACT_HOT_LOADER__.register(DeleteButton, 'DeleteButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/DeleteButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/DeleteButton.js');
}();
;
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var exportCsvBtnDefaultClass = 'react-bs-table-csv-btn';
var ExportCSVButton = function (_Component) {
_inherits(ExportCSVButton, _Component);
function ExportCSVButton() {
_classCallCheck(this, ExportCSVButton);
return _possibleConstructorReturn(this, (ExportCSVButton.__proto__ || Object.getPrototypeOf(ExportCSVButton)).apply(this, arguments));
}
_createClass(ExportCSVButton, [{
key: 'render',
value: function render() {
var _props = this.props,
btnContextual = _props.btnContextual,
className = _props.className,
onClick = _props.onClick,
btnGlyphicon = _props.btnGlyphicon,
btnText = _props.btnText,
children = _props.children,
rest = _objectWithoutProperties(_props, ['btnContextual', 'className', 'onClick', 'btnGlyphicon', 'btnText', 'children']);
var content = children || _react2.default.createElement(
'span',
null,
_react2.default.createElement('i', { className: 'glyphicon ' + btnGlyphicon }),
' ',
btnText
);
return _react2.default.createElement(
'button',
_extends({ type: 'button',
className: 'btn ' + btnContextual + ' ' + exportCsvBtnDefaultClass + ' ' + className + ' hidden-print',
onClick: onClick
}, rest),
content
);
}
}]);
return ExportCSVButton;
}(_react.Component);
ExportCSVButton.propTypes = {
btnText: _react.PropTypes.string,
btnContextual: _react.PropTypes.string,
className: _react.PropTypes.string,
onClick: _react.PropTypes.func,
btnGlyphicon: _react.PropTypes.string
};
ExportCSVButton.defaultProps = {
btnText: _Const2.default.EXPORT_CSV_TEXT,
btnContextual: 'btn-success',
className: '',
onClick: undefined,
btnGlyphicon: 'glyphicon-export'
};
var _default = ExportCSVButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(exportCsvBtnDefaultClass, 'exportCsvBtnDefaultClass', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ExportCSVButton.js');
__REACT_HOT_LOADER__.register(ExportCSVButton, 'ExportCSVButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ExportCSVButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ExportCSVButton.js');
}();
;
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var showSelectedOnlyBtnDefaultClass = 'react-bs-table-show-sel-only-btn';
var ShowSelectedOnlyButton = function (_Component) {
_inherits(ShowSelectedOnlyButton, _Component);
function ShowSelectedOnlyButton() {
_classCallCheck(this, ShowSelectedOnlyButton);
return _possibleConstructorReturn(this, (ShowSelectedOnlyButton.__proto__ || Object.getPrototypeOf(ShowSelectedOnlyButton)).apply(this, arguments));
}
_createClass(ShowSelectedOnlyButton, [{
key: 'render',
value: function render() {
var _props = this.props,
btnContextual = _props.btnContextual,
className = _props.className,
onClick = _props.onClick,
toggle = _props.toggle,
showAllText = _props.showAllText,
showOnlySelectText = _props.showOnlySelectText,
children = _props.children,
rest = _objectWithoutProperties(_props, ['btnContextual', 'className', 'onClick', 'toggle', 'showAllText', 'showOnlySelectText', 'children']);
var content = children || _react2.default.createElement(
'span',
null,
toggle ? showOnlySelectText : showAllText
);
return _react2.default.createElement(
'button',
_extends({ type: 'button',
'aria-pressed': 'false',
'data-toggle': 'button',
className: 'btn ' + btnContextual + ' ' + showSelectedOnlyBtnDefaultClass + ' ' + className,
onClick: onClick
}, rest),
content
);
}
}]);
return ShowSelectedOnlyButton;
}(_react.Component);
ShowSelectedOnlyButton.propTypes = {
showAllText: _react.PropTypes.string,
showOnlySelectText: _react.PropTypes.string,
toggle: _react.PropTypes.bool,
btnContextual: _react.PropTypes.string,
className: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
ShowSelectedOnlyButton.defaultProps = {
showAllText: _Const2.default.SHOW_ALL,
showOnlySelectText: _Const2.default.SHOW_ONLY_SELECT,
toggle: false,
btnContextual: 'btn-primary',
className: '',
onClick: undefined
};
var _default = ShowSelectedOnlyButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(showSelectedOnlyBtnDefaultClass, 'showSelectedOnlyBtnDefaultClass', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ShowSelectedOnlyButton.js');
__REACT_HOT_LOADER__.register(ShowSelectedOnlyButton, 'ShowSelectedOnlyButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ShowSelectedOnlyButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ShowSelectedOnlyButton.js');
}();
;
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SearchField = function (_Component) {
_inherits(SearchField, _Component);
function SearchField() {
_classCallCheck(this, SearchField);
return _possibleConstructorReturn(this, (SearchField.__proto__ || Object.getPrototypeOf(SearchField)).apply(this, arguments));
}
_createClass(SearchField, [{
key: 'getValue',
value: function getValue() {
return _reactDom2.default.findDOMNode(this).value;
}
}, {
key: 'setValue',
value: function setValue(value) {
_reactDom2.default.findDOMNode(this).value = value;
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
className = _props.className,
defaultValue = _props.defaultValue,
placeholder = _props.placeholder,
onKeyUp = _props.onKeyUp,
rest = _objectWithoutProperties(_props, ['className', 'defaultValue', 'placeholder', 'onKeyUp']);
return _react2.default.createElement('input', _extends({
className: 'form-control ' + className,
type: 'text',
defaultValue: defaultValue,
placeholder: placeholder || SearchField.defaultProps.placeholder,
onKeyUp: onKeyUp,
style: { zIndex: 0 }
}, rest));
}
}]);
return SearchField;
}(_react.Component);
SearchField.propTypes = {
className: _react.PropTypes.string,
defaultValue: _react.PropTypes.string,
placeholder: _react.PropTypes.string,
onKeyUp: _react.PropTypes.func
};
SearchField.defaultProps = {
className: '',
defaultValue: '',
placeholder: 'Search',
onKeyUp: undefined
};
var _default = SearchField;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(SearchField, 'SearchField', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/SearchField.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/SearchField.js');
}();
;
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var clearBtnDefaultClass = 'react-bs-table-search-clear-btn';
var ClearSearchButton = function (_Component) {
_inherits(ClearSearchButton, _Component);
function ClearSearchButton() {
_classCallCheck(this, ClearSearchButton);
return _possibleConstructorReturn(this, (ClearSearchButton.__proto__ || Object.getPrototypeOf(ClearSearchButton)).apply(this, arguments));
}
_createClass(ClearSearchButton, [{
key: 'render',
value: function render() {
var _props = this.props,
btnContextual = _props.btnContextual,
className = _props.className,
onClick = _props.onClick,
btnText = _props.btnText,
children = _props.children,
rest = _objectWithoutProperties(_props, ['btnContextual', 'className', 'onClick', 'btnText', 'children']);
var content = children || _react2.default.createElement(
'span',
null,
btnText
);
return _react2.default.createElement(
'button',
_extends({ ref: 'btn',
className: 'btn ' + btnContextual + ' ' + className + ' ' + clearBtnDefaultClass,
type: 'button',
onClick: onClick
}, rest),
content
);
}
}]);
return ClearSearchButton;
}(_react.Component);
ClearSearchButton.propTypes = {
btnContextual: _react.PropTypes.string,
className: _react.PropTypes.string,
btnText: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
ClearSearchButton.defaultProps = {
btnContextual: 'btn-default',
className: '',
btnText: 'Clear',
onClick: undefined
};
var _default = ClearSearchButton;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(clearBtnDefaultClass, 'clearBtnDefaultClass', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ClearSearchButton.js');
__REACT_HOT_LOADER__.register(ClearSearchButton, 'ClearSearchButton', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ClearSearchButton.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ClearSearchButton.js');
}();
;
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TableFilter = function (_Component) {
_inherits(TableFilter, _Component);
function TableFilter(props) {
_classCallCheck(this, TableFilter);
var _this = _possibleConstructorReturn(this, (TableFilter.__proto__ || Object.getPrototypeOf(TableFilter)).call(this, props));
_this.handleKeyUp = function () {
return _this.__handleKeyUp__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.filterObj = {};
return _this;
}
_createClass(TableFilter, [{
key: '__handleKeyUp__REACT_HOT_LOADER__',
value: function __handleKeyUp__REACT_HOT_LOADER__(e) {
var _e$currentTarget = e.currentTarget,
value = _e$currentTarget.value,
name = _e$currentTarget.name;
if (value.trim() === '') {
delete this.filterObj[name];
} else {
this.filterObj[name] = value;
}
this.props.onFilter(this.filterObj);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
striped = _props.striped,
condensed = _props.condensed,
rowSelectType = _props.rowSelectType,
columns = _props.columns;
var tableClasses = (0, _classnames2.default)('table', {
'table-striped': striped,
'table-condensed': condensed
});
var selectRowHeader = null;
if (rowSelectType === _Const2.default.ROW_SELECT_SINGLE || rowSelectType === _Const2.default.ROW_SELECT_MULTI) {
var style = {
width: 35,
paddingLeft: 0,
paddingRight: 0
};
selectRowHeader = _react2.default.createElement(
'th',
{ style: style, key: -1 },
'Filter'
);
}
var filterField = columns.map(function (column) {
var hidden = column.hidden,
width = column.width,
name = column.name;
var thStyle = {
display: hidden ? 'none' : null,
width: width
};
return _react2.default.createElement(
'th',
{ key: name, style: thStyle },
_react2.default.createElement(
'div',
{ className: 'th-inner table-header-column' },
_react2.default.createElement('input', { size: '10', type: 'text',
placeholder: name, name: name, onKeyUp: this.handleKeyUp })
)
);
}, this);
return _react2.default.createElement(
'table',
{ className: tableClasses, style: { marginTop: 5 } },
_react2.default.createElement(
'thead',
null,
_react2.default.createElement(
'tr',
{ style: { borderBottomStyle: 'hidden' } },
selectRowHeader,
filterField
)
)
);
}
}]);
return TableFilter;
}(_react.Component);
TableFilter.propTypes = {
columns: _react.PropTypes.array,
rowSelectType: _react.PropTypes.string,
onFilter: _react.PropTypes.func
};
var _default = TableFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableFilter, 'TableFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableFilter.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableFilter.js');
}();
;
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TableDataStore = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* eslint no-nested-ternary: 0 */
/* eslint guard-for-in: 0 */
/* eslint no-console: 0 */
/* eslint eqeqeq: 0 */
/* eslint one-var: 0 */
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
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 TableDataStore = function () {
function TableDataStore(data) {
_classCallCheck(this, TableDataStore);
this.data = data;
this.colInfos = null;
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
this.searchText = null;
this.sortList = [];
this.pageObj = {};
this.selected = [];
this.multiColumnSearch = false;
this.multiColumnSort = 1;
this.showOnlySelected = false;
this.remote = false; // remote data
}
_createClass(TableDataStore, [{
key: 'setProps',
value: function setProps(props) {
this.keyField = props.keyField;
this.enablePagination = props.isPagination;
this.colInfos = props.colInfos;
this.remote = props.remote;
this.multiColumnSearch = props.multiColumnSearch;
this.multiColumnSort = props.multiColumnSort;
}
}, {
key: 'clean',
value: function clean() {
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
this.searchText = null;
this.sortList = [];
this.pageObj = {};
this.selected = [];
}
}, {
key: 'setData',
value: function setData(data) {
this.data = data;
if (this.remote) {
return;
}
this._refresh(true);
}
}, {
key: 'getColInfos',
value: function getColInfos() {
return this.colInfos;
}
}, {
key: 'getSortInfo',
value: function getSortInfo() {
return this.sortList;
}
}, {
key: 'setSortInfo',
value: function setSortInfo(order, sortField) {
if ((typeof order === 'undefined' ? 'undefined' : _typeof(order)) !== (typeof sortField === 'undefined' ? 'undefined' : _typeof(sortField))) {
throw new Error('The type of sort field and order should be both with String or Array');
}
if (Array.isArray(order) && Array.isArray(sortField)) {
if (order.length !== sortField.length) {
throw new Error('The length of sort fields and orders should be equivalent');
}
order = order.slice().reverse();
this.sortList = sortField.slice().reverse().map(function (field, i) {
return {
order: order[i],
sortField: field
};
});
this.sortList = this.sortList.slice(0, this.multiColumnSort);
} else {
var sortObj = {
order: order,
sortField: sortField
};
if (this.multiColumnSort > 1) {
var i = this.sortList.length - 1;
var sortFieldInHistory = false;
for (; i >= 0; i--) {
if (this.sortList[i].sortField === sortField) {
sortFieldInHistory = true;
break;
}
}
if (sortFieldInHistory) {
if (i > 0) {
this.sortList = this.sortList.slice(0, i);
} else {
this.sortList = this.sortList.slice(1);
}
}
this.sortList.unshift(sortObj);
this.sortList = this.sortList.slice(0, this.multiColumnSort);
} else {
this.sortList = [sortObj];
}
}
}
}, {
key: 'setSelectedRowKey',
value: function setSelectedRowKey(selectedRowKeys) {
this.selected = selectedRowKeys;
}
}, {
key: 'getRowByKey',
value: function getRowByKey(keys) {
var _this = this;
return keys.map(function (key) {
var result = _this.data.filter(function (d) {
return d[_this.keyField] === key;
});
if (result.length !== 0) return result[0];
});
}
}, {
key: 'getSelectedRowKeys',
value: function getSelectedRowKeys() {
return this.selected;
}
}, {
key: 'getCurrentDisplayData',
value: function getCurrentDisplayData() {
if (this.isOnFilter) return this.filteredData;else return this.data;
}
}, {
key: '_refresh',
value: function _refresh(skipSorting) {
if (this.isOnFilter) {
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
if (!skipSorting && this.sortList.length > 0) {
this.sort();
}
}
}, {
key: 'ignoreNonSelected',
value: function ignoreNonSelected() {
var _this2 = this;
this.showOnlySelected = !this.showOnlySelected;
if (this.showOnlySelected) {
this.isOnFilter = true;
this.filteredData = this.data.filter(function (row) {
var result = _this2.selected.find(function (x) {
return row[_this2.keyField] === x;
});
return typeof result !== 'undefined' ? true : false;
});
} else {
this.isOnFilter = false;
}
}
}, {
key: 'sort',
value: function sort() {
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData = this._sort(currentDisplayData);
return this;
}
}, {
key: 'page',
value: function page(_page, sizePerPage) {
this.pageObj.end = _page * sizePerPage - 1;
this.pageObj.start = this.pageObj.end - (sizePerPage - 1);
return this;
}
}, {
key: 'edit',
value: function edit(newVal, rowIndex, fieldName) {
var currentDisplayData = this.getCurrentDisplayData();
var rowKeyCache = void 0;
if (!this.enablePagination) {
currentDisplayData[rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[rowIndex][this.keyField];
} else {
currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField];
}
if (this.isOnFilter) {
this.data.forEach(function (row) {
if (row[this.keyField] === rowKeyCache) {
row[fieldName] = newVal;
}
}, this);
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
return this;
}
}, {
key: 'addAtBegin',
value: function addAtBegin(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw new Error(this.keyField + ' can\'t be empty value.');
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw new Error(this.keyField + ' ' + newObj[this.keyField] + ' already exists');
}
}, this);
currentDisplayData.unshift(newObj);
if (this.isOnFilter) {
this.data.unshift(newObj);
}
this._refresh(false);
}
}, {
key: 'add',
value: function add(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw new Error(this.keyField + ' can\'t be empty value.');
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw new Error(this.keyField + ' ' + newObj[this.keyField] + ' already exists');
}
}, this);
currentDisplayData.push(newObj);
if (this.isOnFilter) {
this.data.push(newObj);
}
this._refresh(false);
}
}, {
key: 'remove',
value: function remove(rowKey) {
var _this3 = this;
var currentDisplayData = this.getCurrentDisplayData();
var result = currentDisplayData.filter(function (row) {
return rowKey.indexOf(row[_this3.keyField]) === -1;
});
if (this.isOnFilter) {
this.data = this.data.filter(function (row) {
return rowKey.indexOf(row[_this3.keyField]) === -1;
});
this.filteredData = result;
} else {
this.data = result;
}
}
}, {
key: 'filter',
value: function filter(filterObj) {
if (Object.keys(filterObj).length === 0) {
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
if (this.searchText) this._search(this.data);
} else {
var source = this.data;
this.filterObj = filterObj;
if (this.searchText) {
this._search(source);
source = this.filteredData;
}
this._filter(source);
}
}
}, {
key: 'filterNumber',
value: function filterNumber(targetVal, filterVal, comparator) {
var valid = true;
switch (comparator) {
case '=':
{
if (targetVal != filterVal) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
if (targetVal < filterVal) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetVal > filterVal) {
valid = false;
}
break;
}
case '!=':
{
if (targetVal == filterVal) {
valid = false;
}
break;
}
default:
{
console.error('Number comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterDate',
value: function filterDate(targetVal, filterVal, comparator) {
if (!targetVal) return false;
var filterDate = filterVal.getDate();
var filterMonth = filterVal.getMonth();
var filterYear = filterVal.getFullYear();
var targetDate = targetVal.getDate();
var targetMonth = targetVal.getMonth();
var targetYear = targetVal.getFullYear();
var valid = true;
switch (comparator) {
case '=':
{
if (filterDate !== targetDate || filterMonth !== targetMonth || filterYear !== targetYear) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
if (targetYear < filterYear) {
valid = false;
} else if (targetYear === filterYear && targetMonth < filterMonth) {
valid = false;
} else if (targetYear === filterYear && targetMonth === filterMonth && targetDate < filterDate) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetYear > filterYear) {
valid = false;
} else if (targetYear === filterYear && targetMonth > filterMonth) {
valid = false;
} else if (targetYear === filterYear && targetMonth === filterMonth && targetDate > filterDate) {
valid = false;
}
break;
}
case '!=':
{
if (filterDate === targetDate && filterMonth === targetMonth && filterYear === targetYear) {
valid = false;
}
break;
}
default:
{
console.error('Date comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterRegex',
value: function filterRegex(targetVal, filterVal) {
try {
return new RegExp(filterVal, 'i').test(targetVal);
} catch (e) {
return true;
}
}
}, {
key: 'filterCustom',
value: function filterCustom(targetVal, filterVal, callbackInfo, cond) {
if (callbackInfo !== null && (typeof callbackInfo === 'undefined' ? 'undefined' : _typeof(callbackInfo)) === 'object') {
return callbackInfo.callback(targetVal, callbackInfo.callbackParameters);
}
return this.filterText(targetVal, filterVal, cond);
}
}, {
key: 'filterText',
value: function filterText(targetVal, filterVal) {
var cond = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _Const2.default.FILTER_COND_LIKE;
targetVal = targetVal.toString();
filterVal = filterVal.toString();
if (cond === _Const2.default.FILTER_COND_EQ) {
return targetVal === filterVal;
} else {
targetVal = targetVal.toLowerCase();
filterVal = filterVal.toLowerCase();
return !(targetVal.indexOf(filterVal) === -1);
}
}
/* General search function
* It will search for the text if the input includes that text;
*/
}, {
key: 'search',
value: function search(searchText) {
if (searchText.trim() === '') {
this.filteredData = null;
this.isOnFilter = false;
this.searchText = null;
if (this.filterObj) this._filter(this.data);
} else {
var source = this.data;
this.searchText = searchText;
if (this.filterObj) {
this._filter(source);
source = this.filteredData;
}
this._search(source);
}
}
}, {
key: '_filter',
value: function _filter(source) {
var _this4 = this;
var filterObj = this.filterObj;
this.filteredData = source.filter(function (row, r) {
var valid = true;
var filterVal = void 0;
for (var key in filterObj) {
var targetVal = row[key];
if (targetVal === null || targetVal === undefined) {
targetVal = '';
}
switch (filterObj[key].type) {
case _Const2.default.FILTER_TYPE.NUMBER:
{
filterVal = filterObj[key].value.number;
break;
}
case _Const2.default.FILTER_TYPE.CUSTOM:
{
filterVal = _typeof(filterObj[key].value) === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
break;
}
case _Const2.default.FILTER_TYPE.DATE:
{
filterVal = filterObj[key].value.date;
break;
}
case _Const2.default.FILTER_TYPE.REGEX:
{
filterVal = filterObj[key].value;
break;
}
default:
{
filterVal = filterObj[key].value;
if (filterVal === undefined) {
// Support old filter
filterVal = filterObj[key];
}
break;
}
}
var format = void 0,
filterFormatted = void 0,
formatExtraData = void 0,
filterValue = void 0;
if (_this4.colInfos[key]) {
format = _this4.colInfos[key].format;
filterFormatted = _this4.colInfos[key].filterFormatted;
formatExtraData = _this4.colInfos[key].formatExtraData;
filterValue = _this4.colInfos[key].filterValue;
if (filterFormatted && format) {
targetVal = format(row[key], row, formatExtraData, r);
} else if (filterValue) {
targetVal = filterValue(row[key], row);
}
}
switch (filterObj[key].type) {
case _Const2.default.FILTER_TYPE.NUMBER:
{
valid = _this4.filterNumber(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2.default.FILTER_TYPE.DATE:
{
valid = _this4.filterDate(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2.default.FILTER_TYPE.REGEX:
{
valid = _this4.filterRegex(targetVal, filterVal);
break;
}
case _Const2.default.FILTER_TYPE.CUSTOM:
{
var cond = filterObj[key].props ? filterObj[key].props.cond : _Const2.default.FILTER_COND_LIKE;
valid = _this4.filterCustom(targetVal, filterVal, filterObj[key].value, cond);
break;
}
default:
{
if (filterObj[key].type === _Const2.default.FILTER_TYPE.SELECT && filterFormatted && filterFormatted && format) {
filterVal = format(filterVal, row, formatExtraData, r);
}
var _cond = filterObj[key].props ? filterObj[key].props.cond : _Const2.default.FILTER_COND_LIKE;
valid = _this4.filterText(targetVal, filterVal, _cond);
break;
}
}
if (!valid) {
break;
}
}
return valid;
});
this.isOnFilter = true;
}
}, {
key: '_search',
value: function _search(source) {
var _this5 = this;
var searchTextArray = [];
if (this.multiColumnSearch) {
searchTextArray = this.searchText.split(' ');
} else {
searchTextArray.push(this.searchText);
}
this.filteredData = source.filter(function (row, r) {
var keys = Object.keys(row);
var valid = false;
// for loops are ugly, but performance matters here.
// And you cant break from a forEach.
// http://jsperf.com/for-vs-foreach/66
for (var i = 0, keysLength = keys.length; i < keysLength; i++) {
var key = keys[i];
// fixed data filter when misunderstand 0 is false
var filterSpecialNum = false;
if (!isNaN(row[key]) && parseInt(row[key], 10) === 0) {
filterSpecialNum = true;
}
if (_this5.colInfos[key] && (row[key] || filterSpecialNum)) {
var _colInfos$key = _this5.colInfos[key],
format = _colInfos$key.format,
filterFormatted = _colInfos$key.filterFormatted,
filterValue = _colInfos$key.filterValue,
formatExtraData = _colInfos$key.formatExtraData,
searchable = _colInfos$key.searchable;
var targetVal = row[key];
if (searchable) {
if (filterFormatted && format) {
targetVal = format(targetVal, row, formatExtraData, r);
} else if (filterValue) {
targetVal = filterValue(targetVal, row);
}
for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) {
var filterVal = searchTextArray[j].toLowerCase();
if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) {
valid = true;
break;
}
}
}
}
}
return valid;
});
this.isOnFilter = true;
}
}, {
key: '_sort',
value: function _sort(arr) {
var _this6 = this;
if (this.sortList.length === 0 || typeof this.sortList[0] === 'undefined') {
return arr;
}
arr.sort(function (a, b) {
var result = 0;
for (var i = 0; i < _this6.sortList.length; i++) {
var sortDetails = _this6.sortList[i];
var isDesc = sortDetails.order.toLowerCase() === _Const2.default.SORT_DESC;
var _colInfos$sortDetails = _this6.colInfos[sortDetails.sortField],
sortFunc = _colInfos$sortDetails.sortFunc,
sortFuncExtraData = _colInfos$sortDetails.sortFuncExtraData;
if (sortFunc) {
result = sortFunc(a, b, sortDetails.order, sortDetails.sortField, sortFuncExtraData);
} else {
var valueA = a[sortDetails.sortField] === null ? '' : a[sortDetails.sortField];
var valueB = b[sortDetails.sortField] === null ? '' : b[sortDetails.sortField];
if (isDesc) {
if (typeof valueB === 'string') {
result = valueB.localeCompare(valueA);
} else {
result = valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
}
} else {
if (typeof valueA === 'string') {
result = valueA.localeCompare(valueB);
} else {
result = valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
}
}
}
if (result !== 0) {
return result;
}
}
return result;
});
return arr;
}
}, {
key: 'getDataIgnoringPagination',
value: function getDataIgnoringPagination() {
return this.getCurrentDisplayData();
}
}, {
key: 'get',
value: function get() {
var _data = this.getCurrentDisplayData();
if (_data.length === 0) return _data;
var remote = typeof this.remote === 'function' ? this.remote(_Const2.default.REMOTE)[_Const2.default.REMOTE_PAGE] : this.remote;
if (remote || !this.enablePagination) {
return _data;
} else {
var result = [];
for (var i = this.pageObj.start; i <= this.pageObj.end; i++) {
result.push(_data[i]);
if (i + 1 === _data.length) break;
}
return result;
}
}
}, {
key: 'getKeyField',
value: function getKeyField() {
return this.keyField;
}
}, {
key: 'getDataNum',
value: function getDataNum() {
return this.getCurrentDisplayData().length;
}
}, {
key: 'isChangedPage',
value: function isChangedPage() {
return this.pageObj.start && this.pageObj.end ? true : false;
}
}, {
key: 'isEmpty',
value: function isEmpty() {
return this.data.length === 0 || this.data === null || this.data === undefined;
}
}, {
key: 'getAllRowkey',
value: function getAllRowkey() {
var _this7 = this;
return this.data.map(function (row) {
return row[_this7.keyField];
});
}
}]);
return TableDataStore;
}();
exports.TableDataStore = TableDataStore;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableDataStore, 'TableDataStore', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/store/TableDataStore.js');
}();
;
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
if (_util2.default.canUseDOM()) {
var filesaver = __webpack_require__(207);
var saveAs = filesaver.saveAs;
} /* eslint block-scoped-var: 0 */
/* eslint vars-on-top: 0 */
/* eslint no-var: 0 */
/* eslint no-unused-vars: 0 */
function toString(data, keys) {
var dataString = '';
if (data.length === 0) return dataString;
var headCells = [];
var rowCount = 0;
keys.forEach(function (key) {
if (key.row > rowCount) {
rowCount = key.row;
}
// rowCount += (key.rowSpan + key.colSpan - 1);
for (var index = 0; index < key.colSpan; index++) {
headCells.push(key);
}
});
var _loop = function _loop(i) {
dataString += headCells.map(function (x) {
if (x.row + (x.rowSpan - 1) === i) {
return x.header;
}
if (x.row === i && x.rowSpan > 1) {
return '';
}
}).filter(function (key) {
return typeof key !== 'undefined';
}).join(',') + '\n';
};
for (var i = 0; i <= rowCount; i++) {
_loop(i);
}
keys = keys.filter(function (key) {
return key.field !== undefined;
});
data.map(function (row) {
keys.map(function (col, i) {
var field = col.field,
format = col.format,
extraData = col.extraData;
var value = typeof format !== 'undefined' ? format(row[field], row, extraData) : row[field];
var cell = typeof value !== 'undefined' ? '"' + value + '"' : '';
dataString += cell;
if (i + 1 < keys.length) dataString += ',';
});
dataString += '\n';
});
return dataString;
}
var exportCSV = function exportCSV(data, keys, filename) {
var dataString = toString(data, keys);
if (typeof window !== 'undefined') {
saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename, true);
}
};
var _default = exportCSV;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(saveAs, 'saveAs', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js');
__REACT_HOT_LOADER__.register(toString, 'toString', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js');
__REACT_HOT_LOADER__.register(exportCSV, 'exportCSV', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/csv_export_util.js');
}();
;
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.3.2
* 2016-06-16 18:25:19
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || function (view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet
,
get_URL = function get_URL() {
return view.URL || view.webkitURL || view;
},
save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
can_use_save_link = "download" in save_link,
click = function click(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
},
is_safari = /constructor/i.test(view.HTMLElement) || view.safari,
is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent),
throw_outside = function throw_outside(ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
},
force_saveable_type = "application/octet-stream"
// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
,
arbitrary_revoke_timeout = 1000 * 40 // in ms
,
revoke = function revoke(file) {
var revoker = function revoker() {
if (typeof file === "string") {
// file is an object URL
get_URL().revokeObjectURL(file);
} else {
// file is a File
file.remove();
}
};
setTimeout(revoker, arbitrary_revoke_timeout);
},
dispatch = function dispatch(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
},
auto_bom = function auto_bom(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type });
}
return blob;
},
FileSaver = function FileSaver(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var filesaver = this,
type = blob.type,
force = type === force_saveable_type,
object_url,
dispatch_all = function dispatch_all() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
,
fs_error = function fs_error() {
if ((is_chrome_ios || force && is_safari) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function () {
var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
var popup = view.open(url, '_blank');
if (!popup) view.location.href = url;
url = undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, "_blank");
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
};
filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function () {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
fs_error();
},
FS_proto = FileSaver.prototype,
saveAs = function saveAs(blob, name, no_auto_bom) {
return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
};
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function (blob, name, no_auto_bom) {
name = name || blob.name || "download";
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name);
};
}
FS_proto.abort = function () {};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs;
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ("function" !== "undefined" && __webpack_require__(208) !== null && __webpack_require__(209) !== null) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return saveAs;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(saveAs, "saveAs", "/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filesaver.js");
}();
;
/***/ },
/* 208 */
/***/ function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ },
/* 209 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 210 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Filter = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _events = __webpack_require__(211);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Filter = exports.Filter = function (_EventEmitter) {
_inherits(Filter, _EventEmitter);
function Filter(data) {
_classCallCheck(this, Filter);
var _this = _possibleConstructorReturn(this, (Filter.__proto__ || Object.getPrototypeOf(Filter)).call(this, data));
_this.currentFilter = {};
return _this;
}
_createClass(Filter, [{
key: 'handleFilter',
value: function handleFilter(dataField, value, type, filterObj) {
var filterType = type || _Const2.default.FILTER_TYPE.CUSTOM;
var props = {
cond: filterObj.condition // Only for select and text filter
};
if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
// value of the filter is an object
var hasValue = true;
for (var prop in value) {
if (!value[prop] || value[prop] === '') {
hasValue = false;
break;
}
}
// if one of the object properties is undefined or empty, we remove the filter
if (hasValue) {
this.currentFilter[dataField] = { value: value, type: filterType, props: props };
} else {
delete this.currentFilter[dataField];
}
} else if (!value || value.trim() === '') {
delete this.currentFilter[dataField];
} else {
this.currentFilter[dataField] = { value: value.trim(), type: filterType, props: props };
}
this.emit('onFilterChange', this.currentFilter);
}
}]);
return Filter;
}(_events.EventEmitter);
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(Filter, 'Filter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/Filter.js');
}();
;
/***/ },
/* 211 */
/***/ function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
var _Date = __webpack_require__(213);
var _Date2 = _interopRequireDefault(_Date);
var _Text = __webpack_require__(214);
var _Text2 = _interopRequireDefault(_Text);
var _Regex = __webpack_require__(215);
var _Regex2 = _interopRequireDefault(_Regex);
var _Select = __webpack_require__(216);
var _Select2 = _interopRequireDefault(_Select);
var _Number = __webpack_require__(217);
var _Number2 = _interopRequireDefault(_Number);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint default-case: 0 */
/* eslint guard-for-in: 0 */
var TableHeaderColumn = function (_Component) {
_inherits(TableHeaderColumn, _Component);
function TableHeaderColumn(props) {
_classCallCheck(this, TableHeaderColumn);
var _this = _possibleConstructorReturn(this, (TableHeaderColumn.__proto__ || Object.getPrototypeOf(TableHeaderColumn)).call(this, props));
_this.handleColumnClick = function () {
return _this.__handleColumnClick__REACT_HOT_LOADER__.apply(_this, arguments);
};
_this.handleFilter = _this.handleFilter.bind(_this);
return _this;
}
_createClass(TableHeaderColumn, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.reset) {
this.cleanFiltered();
}
}
}, {
key: '__handleColumnClick__REACT_HOT_LOADER__',
value: function __handleColumnClick__REACT_HOT_LOADER__() {
if (this.props.isOnlyHead || !this.props.dataSort) return;
var order = this.props.sort === _Const2.default.SORT_DESC ? _Const2.default.SORT_ASC : _Const2.default.SORT_DESC;
this.props.onSort(order, this.props.dataField);
}
}, {
key: 'handleFilter',
value: function handleFilter(value, type) {
var filter = this.props.filter;
filter.emitter.handleFilter(this.props.dataField, value, type, filter);
}
}, {
key: 'getFilters',
value: function getFilters() {
var _props = this.props,
headerText = _props.headerText,
children = _props.children;
switch (this.props.filter.type) {
case _Const2.default.FILTER_TYPE.TEXT:
{
return _react2.default.createElement(_Text2.default, _extends({ ref: 'textFilter' }, this.props.filter, {
columnName: headerText || children, filterHandler: this.handleFilter }));
}
case _Const2.default.FILTER_TYPE.REGEX:
{
return _react2.default.createElement(_Regex2.default, _extends({ ref: 'regexFilter' }, this.props.filter, {
columnName: headerText || children, filterHandler: this.handleFilter }));
}
case _Const2.default.FILTER_TYPE.SELECT:
{
return _react2.default.createElement(_Select2.default, _extends({ ref: 'selectFilter' }, this.props.filter, {
columnName: headerText || children, filterHandler: this.handleFilter }));
}
case _Const2.default.FILTER_TYPE.NUMBER:
{
return _react2.default.createElement(_Number2.default, _extends({ ref: 'numberFilter' }, this.props.filter, {
columnName: headerText || children, filterHandler: this.handleFilter }));
}
case _Const2.default.FILTER_TYPE.DATE:
{
return _react2.default.createElement(_Date2.default, _extends({ ref: 'dateFilter' }, this.props.filter, {
columnName: headerText || children, filterHandler: this.handleFilter }));
}
case _Const2.default.FILTER_TYPE.CUSTOM:
{
var elm = this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters);
return _react2.default.cloneElement(elm, { ref: 'customFilter' });
}
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs['header-col'].setAttribute('data-field', this.props.dataField);
}
}, {
key: 'render',
value: function render() {
var defaultCaret = void 0;
var sortCaret = void 0;
var _props2 = this.props,
headerText = _props2.headerText,
dataAlign = _props2.dataAlign,
dataField = _props2.dataField,
headerAlign = _props2.headerAlign,
headerTitle = _props2.headerTitle,
hidden = _props2.hidden,
sort = _props2.sort,
dataSort = _props2.dataSort,
sortIndicator = _props2.sortIndicator,
children = _props2.children,
caretRender = _props2.caretRender,
className = _props2.className,
isOnlyHead = _props2.isOnlyHead,
style = _props2.thStyle;
var thStyle = _extends({
textAlign: headerAlign || dataAlign,
display: hidden ? 'none' : null
}, style);
if (!isOnlyHead) {
if (sortIndicator) {
defaultCaret = !dataSort ? null : _react2.default.createElement(
'span',
{ className: 'order' },
_react2.default.createElement(
'span',
{ className: 'dropdown' },
_react2.default.createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } })
),
_react2.default.createElement(
'span',
{ className: 'dropup' },
_react2.default.createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } })
)
);
}
sortCaret = sort ? _util2.default.renderReactSortCaret(sort) : defaultCaret;
if (caretRender) {
sortCaret = caretRender(sort, dataField);
}
}
var classes = (0, _classnames2.default)(typeof className === 'function' ? className() : className, !isOnlyHead && dataSort ? 'sort-column' : '');
var title = {
title: headerTitle && typeof children === 'string' ? children : headerText
};
return _react2.default.createElement(
'th',
_extends({ ref: 'header-col',
className: classes,
style: thStyle,
onClick: this.handleColumnClick,
rowSpan: this.props.rowSpan,
colSpan: this.props.colSpan,
'data-is-only-head': this.props.isOnlyHead
}, title),
children,
sortCaret,
_react2.default.createElement(
'div',
{ onClick: function onClick(e) {
return e.stopPropagation();
} },
this.props.filter && !isOnlyHead ? this.getFilters() : null
)
);
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
if (this.props.filter === undefined) {
return;
}
switch (this.props.filter.type) {
case _Const2.default.FILTER_TYPE.TEXT:
{
this.refs.textFilter.cleanFiltered();
break;
}
case _Const2.default.FILTER_TYPE.REGEX:
{
this.refs.regexFilter.cleanFiltered();
break;
}
case _Const2.default.FILTER_TYPE.SELECT:
{
this.refs.selectFilter.cleanFiltered();
break;
}
case _Const2.default.FILTER_TYPE.NUMBER:
{
this.refs.numberFilter.cleanFiltered();
break;
}
case _Const2.default.FILTER_TYPE.DATE:
{
this.refs.dateFilter.cleanFiltered();
break;
}
case _Const2.default.FILTER_TYPE.CUSTOM:
{
this.refs.customFilter.cleanFiltered();
break;
}
}
}
}, {
key: 'applyFilter',
value: function applyFilter(val) {
if (this.props.filter === undefined) return;
switch (this.props.filter.type) {
case _Const2.default.FILTER_TYPE.TEXT:
{
this.refs.textFilter.applyFilter(val);
break;
}
case _Const2.default.FILTER_TYPE.REGEX:
{
this.refs.regexFilter.applyFilter(val);
break;
}
case _Const2.default.FILTER_TYPE.SELECT:
{
this.refs.selectFilter.applyFilter(val);
break;
}
case _Const2.default.FILTER_TYPE.NUMBER:
{
this.refs.numberFilter.applyFilter(val);
break;
}
case _Const2.default.FILTER_TYPE.DATE:
{
this.refs.dateFilter.applyFilter(val);
break;
}
}
}
}]);
return TableHeaderColumn;
}(_react.Component);
var filterTypeArray = [];
for (var key in _Const2.default.FILTER_TYPE) {
filterTypeArray.push(_Const2.default.FILTER_TYPE[key]);
}
TableHeaderColumn.propTypes = {
dataField: _react.PropTypes.string,
dataAlign: _react.PropTypes.string,
headerAlign: _react.PropTypes.string,
headerTitle: _react.PropTypes.bool,
headerText: _react.PropTypes.string,
dataSort: _react.PropTypes.bool,
onSort: _react.PropTypes.func,
dataFormat: _react.PropTypes.func,
csvFormat: _react.PropTypes.func,
csvHeader: _react.PropTypes.string,
isKey: _react.PropTypes.bool,
editable: _react.PropTypes.any,
hidden: _react.PropTypes.bool,
hiddenOnInsert: _react.PropTypes.bool,
searchable: _react.PropTypes.bool,
className: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]),
width: _react.PropTypes.string,
sortFunc: _react.PropTypes.func,
sortFuncExtraData: _react.PropTypes.any,
columnClassName: _react.PropTypes.any,
editColumnClassName: _react.PropTypes.any,
invalidEditColumnClassName: _react.PropTypes.any,
columnTitle: _react.PropTypes.bool,
filterFormatted: _react.PropTypes.bool,
filterValue: _react.PropTypes.func,
sort: _react.PropTypes.string,
caretRender: _react.PropTypes.func,
formatExtraData: _react.PropTypes.any,
csvFormatExtraData: _react.PropTypes.any,
filter: _react.PropTypes.shape({
type: _react.PropTypes.oneOf(filterTypeArray),
delay: _react.PropTypes.number,
options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter
_react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter
]),
numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string),
emitter: _react.PropTypes.object,
placeholder: _react.PropTypes.string,
getElement: _react.PropTypes.func,
customFilterParameters: _react.PropTypes.object,
condition: _react.PropTypes.oneOf([_Const2.default.FILTER_COND_EQ, _Const2.default.FILTER_COND_LIKE])
}),
sortIndicator: _react.PropTypes.bool,
export: _react.PropTypes.bool,
expandable: _react.PropTypes.bool,
tdAttr: _react.PropTypes.object,
tdStyle: _react.PropTypes.object,
thStyle: _react.PropTypes.object
};
TableHeaderColumn.defaultProps = {
dataAlign: 'left',
headerAlign: undefined,
headerTitle: true,
dataSort: false,
dataFormat: undefined,
csvFormat: undefined,
csvHeader: undefined,
isKey: false,
editable: true,
onSort: undefined,
hidden: false,
hiddenOnInsert: false,
searchable: true,
className: '',
columnTitle: false,
width: null,
sortFunc: undefined,
columnClassName: '',
editColumnClassName: '',
invalidEditColumnClassName: '',
filterFormatted: false,
filterValue: undefined,
sort: undefined,
formatExtraData: undefined,
sortFuncExtraData: undefined,
filter: undefined,
sortIndicator: true,
expandable: true,
tdAttr: undefined,
tdStyle: undefined,
thStyle: undefined
};
var _default = TableHeaderColumn;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TableHeaderColumn, 'TableHeaderColumn', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js');
__REACT_HOT_LOADER__.register(filterTypeArray, 'filterTypeArray', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/TableHeaderColumn.js');
}();
;
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint quotes: 0 */
/* eslint max-len: 0 */
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
function dateParser(d) {
return d.getFullYear() + '-' + ("0" + (d.getMonth() + 1)).slice(-2) + '-' + ("0" + d.getDate()).slice(-2);
}
var DateFilter = function (_Component) {
_inherits(DateFilter, _Component);
function DateFilter(props) {
_classCallCheck(this, DateFilter);
var _this = _possibleConstructorReturn(this, (DateFilter.__proto__ || Object.getPrototypeOf(DateFilter)).call(this, props));
_this.dateComparators = _this.props.dateComparators || legalComparators;
_this.filter = _this.filter.bind(_this);
_this.onChangeComparator = _this.onChangeComparator.bind(_this);
return _this;
}
_createClass(DateFilter, [{
key: 'setDefaultDate',
value: function setDefaultDate() {
var defaultDate = '';
var defaultValue = this.props.defaultValue;
if (defaultValue && defaultValue.date) {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
defaultDate = dateParser(new Date(defaultValue.date));
}
return defaultDate;
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var date = this.refs.inputDate.value;
var comparator = event.target.value;
if (date === '') {
return;
}
date = new Date(date);
this.props.filterHandler({ date: date, comparator: comparator }, _Const2.default.FILTER_TYPE.DATE);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2.default.createElement('option', { key: '-1' }));
for (var i = 0; i < this.dateComparators.length; i++) {
optionTags.push(_react2.default.createElement(
'option',
{ key: i, value: this.dateComparators[i] },
this.dateComparators[i]
));
}
return optionTags;
}
}, {
key: 'filter',
value: function filter(event) {
var comparator = this.refs.dateFilterComparator.value;
var dateValue = event.target.value;
if (dateValue) {
this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE);
} else {
this.props.filterHandler(null, _Const2.default.FILTER_TYPE.DATE);
}
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
var value = this.setDefaultDate();
var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : '';
this.setState({ isPlaceholderSelected: value === '' });
this.refs.dateFilterComparator.value = comparator;
this.refs.inputDate.value = value;
this.props.filterHandler({ date: new Date(value), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE);
}
}, {
key: 'applyFilter',
value: function applyFilter(filterDateObj) {
var date = filterDateObj.date,
comparator = filterDateObj.comparator;
this.setState({ isPlaceholderSelected: date === '' });
this.refs.dateFilterComparator.value = comparator;
this.refs.inputDate.value = dateParser(date);
this.props.filterHandler({ date: date, comparator: comparator }, _Const2.default.FILTER_TYPE.DATE);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.dateFilterComparator.value;
var dateValue = this.refs.inputDate.value;
if (comparator && dateValue) {
this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2.default.FILTER_TYPE.DATE);
}
}
}, {
key: 'render',
value: function render() {
var defaultValue = this.props.defaultValue;
return _react2.default.createElement(
'div',
{ className: 'filter date-filter' },
_react2.default.createElement(
'select',
{ ref: 'dateFilterComparator',
className: 'date-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: defaultValue ? defaultValue.comparator : '' },
this.getComparatorOptions()
),
_react2.default.createElement('input', { ref: 'inputDate',
className: 'filter date-filter-input form-control',
type: 'date',
onChange: this.filter,
defaultValue: this.setDefaultDate() })
);
}
}]);
return DateFilter;
}(_react.Component);
DateFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.shape({
date: _react.PropTypes.object,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
/* eslint consistent-return: 0 */
dateComparators: function dateComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
columnName: _react.PropTypes.string
};
var _default = DateFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(legalComparators, 'legalComparators', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js');
__REACT_HOT_LOADER__.register(dateParser, 'dateParser', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js');
__REACT_HOT_LOADER__.register(DateFilter, 'DateFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Date.js');
}();
;
/***/ },
/* 214 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TextFilter = function (_Component) {
_inherits(TextFilter, _Component);
function TextFilter(props) {
_classCallCheck(this, TextFilter);
var _this = _possibleConstructorReturn(this, (TextFilter.__proto__ || Object.getPrototypeOf(TextFilter)).call(this, props));
_this.filter = _this.filter.bind(_this);
_this.timeout = null;
return _this;
}
_createClass(TextFilter, [{
key: 'filter',
value: function filter(event) {
var _this2 = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this2.props.filterHandler(filterValue, _Const2.default.FILTER_TYPE.TEXT);
}, this.props.delay);
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
var value = this.props.defaultValue ? this.props.defaultValue : '';
this.refs.inputText.value = value;
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.TEXT);
}
}, {
key: 'applyFilter',
value: function applyFilter(filterText) {
this.refs.inputText.value = filterText;
this.props.filterHandler(filterText, _Const2.default.FILTER_TYPE.TEXT);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var defaultValue = this.refs.inputText.value;
if (defaultValue) {
this.props.filterHandler(defaultValue, _Const2.default.FILTER_TYPE.TEXT);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
placeholder = _props.placeholder,
columnName = _props.columnName,
defaultValue = _props.defaultValue;
return _react2.default.createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return TextFilter;
}(_react.Component);
TextFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
TextFilter.defaultProps = {
delay: _Const2.default.FILTER_DELAY
};
var _default = TextFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(TextFilter, 'TextFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Text.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Text.js');
}();
;
/***/ },
/* 215 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RegexFilter = function (_Component) {
_inherits(RegexFilter, _Component);
function RegexFilter(props) {
_classCallCheck(this, RegexFilter);
var _this = _possibleConstructorReturn(this, (RegexFilter.__proto__ || Object.getPrototypeOf(RegexFilter)).call(this, props));
_this.filter = _this.filter.bind(_this);
_this.timeout = null;
return _this;
}
_createClass(RegexFilter, [{
key: 'filter',
value: function filter(event) {
var _this2 = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this2.props.filterHandler(filterValue, _Const2.default.FILTER_TYPE.REGEX);
}, this.props.delay);
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
var value = this.props.defaultValue ? this.props.defaultValue : '';
this.refs.inputText.value = value;
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.TEXT);
}
}, {
key: 'applyFilter',
value: function applyFilter(filterRegx) {
this.refs.inputText.value = filterRegx;
this.props.filterHandler(filterRegx, _Const2.default.FILTER_TYPE.REGEX);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.inputText.value;
if (value) {
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.REGEX);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
defaultValue = _props.defaultValue,
placeholder = _props.placeholder,
columnName = _props.columnName;
return _react2.default.createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter Regex for ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return RegexFilter;
}(_react.Component);
RegexFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
RegexFilter.defaultProps = {
delay: _Const2.default.FILTER_DELAY
};
var _default = RegexFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(RegexFilter, 'RegexFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Regex.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Regex.js');
}();
;
/***/ },
/* 216 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SelectFilter = function (_Component) {
_inherits(SelectFilter, _Component);
function SelectFilter(props) {
_classCallCheck(this, SelectFilter);
var _this = _possibleConstructorReturn(this, (SelectFilter.__proto__ || Object.getPrototypeOf(SelectFilter)).call(this, props));
_this.filter = _this.filter.bind(_this);
_this.state = {
isPlaceholderSelected: _this.props.defaultValue === undefined || !_this.props.options.hasOwnProperty(_this.props.defaultValue)
};
return _this;
}
_createClass(SelectFilter, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var isPlaceholderSelected = nextProps.defaultValue === undefined || !nextProps.options.hasOwnProperty(nextProps.defaultValue);
this.setState({
isPlaceholderSelected: isPlaceholderSelected
});
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var needFilter = false;
if (this.props.defaultValue !== prevProps.defaultValue) {
needFilter = true;
} else if (this.props.options !== prevProps.options) {
needFilter = true;
}
if (needFilter) {
var value = this.refs.selectInput.value;
if (value) {
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT);
}
}
}
}, {
key: 'filter',
value: function filter(event) {
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT);
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
var value = this.props.defaultValue !== undefined ? this.props.defaultValue : '';
this.setState({ isPlaceholderSelected: value === '' });
this.refs.selectInput.value = value;
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT);
}
}, {
key: 'applyFilter',
value: function applyFilter(filterOption) {
filterOption = filterOption + '';
this.setState({ isPlaceholderSelected: filterOption === '' });
this.refs.selectInput.value = filterOption;
this.props.filterHandler(filterOption, _Const2.default.FILTER_TYPE.SELECT);
}
}, {
key: 'getOptions',
value: function getOptions() {
var optionTags = [];
var _props = this.props,
options = _props.options,
placeholder = _props.placeholder,
columnName = _props.columnName,
selectText = _props.selectText;
var selectTextValue = selectText !== undefined ? selectText : 'Select';
optionTags.push(_react2.default.createElement(
'option',
{ key: '-1', value: '' },
placeholder || selectTextValue + ' ' + columnName + '...'
));
Object.keys(options).map(function (key) {
optionTags.push(_react2.default.createElement(
'option',
{ key: key, value: key },
options[key] + ''
));
});
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.selectInput.value;
if (value) {
this.props.filterHandler(value, _Const2.default.FILTER_TYPE.SELECT);
}
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2.default)('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2.default.createElement(
'select',
{ ref: 'selectInput',
className: selectClass,
onChange: this.filter,
defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' },
this.getOptions()
);
}
}]);
return SelectFilter;
}(_react.Component);
SelectFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.object.isRequired,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
var _default = SelectFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(SelectFilter, 'SelectFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Select.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Select.js');
}();
;
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(3);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(4);
var _Const2 = _interopRequireDefault(_Const);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
var NumberFilter = function (_Component) {
_inherits(NumberFilter, _Component);
function NumberFilter(props) {
_classCallCheck(this, NumberFilter);
var _this = _possibleConstructorReturn(this, (NumberFilter.__proto__ || Object.getPrototypeOf(NumberFilter)).call(this, props));
_this.numberComparators = _this.props.numberComparators || legalComparators;
_this.timeout = null;
_this.state = {
isPlaceholderSelected: _this.props.defaultValue === undefined || _this.props.defaultValue.number === undefined || _this.props.options && _this.props.options.indexOf(_this.props.defaultValue.number) === -1
};
_this.onChangeNumber = _this.onChangeNumber.bind(_this);
_this.onChangeNumberSet = _this.onChangeNumberSet.bind(_this);
_this.onChangeComparator = _this.onChangeComparator.bind(_this);
return _this;
}
_createClass(NumberFilter, [{
key: 'onChangeNumber',
value: function onChangeNumber(event) {
var _this2 = this;
var comparator = this.refs.numberFilterComparator.value;
if (comparator === '') {
return;
}
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this2.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}, this.props.delay);
}
}, {
key: 'onChangeNumberSet',
value: function onChangeNumberSet(event) {
var comparator = this.refs.numberFilterComparator.value;
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
if (comparator === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var value = this.refs.numberFilter.value;
var comparator = event.target.value;
if (value === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}
}, {
key: 'cleanFiltered',
value: function cleanFiltered() {
var value = this.props.defaultValue ? this.props.defaultValue.number : '';
var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : '';
this.setState({ isPlaceholderSelected: value === '' });
this.refs.numberFilterComparator.value = comparator;
this.refs.numberFilter.value = value;
this.props.filterHandler({ number: value, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}
}, {
key: 'applyFilter',
value: function applyFilter(filterObj) {
var number = filterObj.number,
comparator = filterObj.comparator;
this.setState({ isPlaceholderSelected: number === '' });
this.refs.numberFilterComparator.value = comparator;
this.refs.numberFilter.value = number;
this.props.filterHandler({ number: number, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2.default.createElement('option', { key: '-1' }));
for (var i = 0; i < this.numberComparators.length; i++) {
optionTags.push(_react2.default.createElement(
'option',
{ key: i, value: this.numberComparators[i] },
this.numberComparators[i]
));
}
return optionTags;
}
}, {
key: 'getNumberOptions',
value: function getNumberOptions() {
var optionTags = [];
var options = this.props.options;
optionTags.push(_react2.default.createElement(
'option',
{ key: '-1', value: '' },
this.props.placeholder || 'Select ' + this.props.columnName + '...'
));
for (var i = 0; i < options.length; i++) {
optionTags.push(_react2.default.createElement(
'option',
{ key: i, value: options[i] },
options[i]
));
}
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.numberFilterComparator.value;
var number = this.refs.numberFilter.value;
if (comparator && number) {
this.props.filterHandler({ number: number, comparator: comparator }, _Const2.default.FILTER_TYPE.NUMBER);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2.default)('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2.default.createElement(
'div',
{ className: 'filter number-filter' },
_react2.default.createElement(
'select',
{ ref: 'numberFilterComparator',
className: 'number-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' },
this.getComparatorOptions()
),
this.props.options ? _react2.default.createElement(
'select',
{ ref: 'numberFilter',
className: selectClass,
onChange: this.onChangeNumberSet,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' },
this.getNumberOptions()
) : _react2.default.createElement('input', { ref: 'numberFilter',
type: 'number',
className: 'number-filter-input form-control',
placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',
onChange: this.onChangeNumber,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' })
);
}
}]);
return NumberFilter;
}(_react.Component);
NumberFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.arrayOf(_react.PropTypes.number),
defaultValue: _react.PropTypes.shape({
number: _react.PropTypes.number,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
delay: _react.PropTypes.number,
/* eslint consistent-return: 0 */
numberComparators: function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
NumberFilter.defaultProps = {
delay: _Const2.default.FILTER_DELAY
};
var _default = NumberFilter;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(legalComparators, 'legalComparators', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js');
__REACT_HOT_LOADER__.register(NumberFilter, 'NumberFilter', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/filters/Number.js');
}();
;
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ButtonGroup = function (_Component) {
_inherits(ButtonGroup, _Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, (ButtonGroup.__proto__ || Object.getPrototypeOf(ButtonGroup)).apply(this, arguments));
}
_createClass(ButtonGroup, [{
key: 'render',
value: function render() {
var _props = this.props,
className = _props.className,
sizeClass = _props.sizeClass,
children = _props.children,
rest = _objectWithoutProperties(_props, ['className', 'sizeClass', 'children']);
return _react2.default.createElement(
'div',
_extends({ className: 'btn-group ' + sizeClass + ' ' + className, role: 'group' }, rest),
children
);
}
}]);
return ButtonGroup;
}(_react.Component);
ButtonGroup.propTypes = {
sizeClass: _react.PropTypes.string,
className: _react.PropTypes.string
};
ButtonGroup.defaultProps = {
sizeClass: 'btn-group-sm',
className: ''
};
var _default = ButtonGroup;
exports.default = _default;
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(ButtonGroup, 'ButtonGroup', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ButtonGroup.js');
__REACT_HOT_LOADER__.register(_default, 'default', '/Users/allen/Node/react-bootstrap-table-new/react-bootstrap-table/src/toolbar/ButtonGroup.js');
}();
;
/***/ }
/******/ ])
});
;
//# sourceMappingURL=react-bootstrap-table.js.map |
reaction/src/index.js | onespeed-workshops/the-vue-reaction | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './App.css'
ReactDOM.render(<App />, document.getElementById('root'));
|
third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js | endlessm/chromium-browser | /**
* @demo demo/index.html
* @polymerBehavior Polymer.IronButtonState
*/
Polymer.IronButtonStateImpl = {
properties: {
/**
* If true, the user is currently holding down the button.
*/
pressed: {
type: Boolean,
readOnly: true,
value: false,
reflectToAttribute: true,
observer: '_pressedChanged'
},
/**
* If true, the button toggles the active state with each tap or press
* of the spacebar.
*/
toggles: {
type: Boolean,
value: false,
reflectToAttribute: true
},
/**
* If true, the button is a toggle and is currently in the active state.
*/
active: {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true
},
/**
* True if the element is currently being pressed by a "pointer," which
* is loosely defined as mouse or touch input (but specifically excluding
* keyboard input).
*/
pointerDown: {
type: Boolean,
readOnly: true,
value: false
},
/**
* True if the input device that caused the element to receive focus
* was a keyboard.
*/
receivedFocusFromKeyboard: {
type: Boolean,
readOnly: true
},
/**
* The aria attribute to be set if the button is a toggle and in the
* active state.
*/
ariaActiveAttribute: {
type: String,
value: 'aria-pressed',
observer: '_ariaActiveAttributeChanged'
}
},
listeners: {
down: '_downHandler',
up: '_upHandler',
tap: '_tapHandler'
},
observers: [
'_focusChanged(focused)',
'_activeChanged(active, ariaActiveAttribute)'
],
/**
* @type {!Object}
*/
keyBindings: {
'enter:keydown': '_asyncClick',
'space:keydown': '_spaceKeyDownHandler',
'space:keyup': '_spaceKeyUpHandler',
},
_mouseEventRe: /^mouse/,
_tapHandler: function() {
if (this.toggles) {
// a tap is needed to toggle the active state
this._userActivate(!this.active);
} else {
this.active = false;
}
},
_focusChanged: function(focused) {
this._detectKeyboardFocus(focused);
if (!focused) {
this._setPressed(false);
}
},
_detectKeyboardFocus: function(focused) {
this._setReceivedFocusFromKeyboard(!this.pointerDown && focused);
},
// to emulate native checkbox, (de-)activations from a user interaction fire
// 'change' events
_userActivate: function(active) {
if (this.active !== active) {
this.active = active;
this.fire('change');
}
},
_downHandler: function(event) {
this._setPointerDown(true);
this._setPressed(true);
this._setReceivedFocusFromKeyboard(false);
},
_upHandler: function() {
this._setPointerDown(false);
this._setPressed(false);
},
/**
* @param {!KeyboardEvent} event .
*/
_spaceKeyDownHandler: function(event) {
var keyboardEvent = event.detail.keyboardEvent;
var target = Polymer.dom(keyboardEvent).localTarget;
// Ignore the event if this is coming from a focused light child, since that
// element will deal with it.
if (this.isLightDescendant(/** @type {Node} */(target)))
return;
keyboardEvent.preventDefault();
keyboardEvent.stopImmediatePropagation();
this._setPressed(true);
},
/**
* @param {!KeyboardEvent} event .
*/
_spaceKeyUpHandler: function(event) {
var keyboardEvent = event.detail.keyboardEvent;
var target = Polymer.dom(keyboardEvent).localTarget;
// Ignore the event if this is coming from a focused light child, since that
// element will deal with it.
if (this.isLightDescendant(/** @type {Node} */(target)))
return;
if (this.pressed) {
this._asyncClick();
}
this._setPressed(false);
},
// trigger click asynchronously, the asynchrony is useful to allow one
// event handler to unwind before triggering another event
_asyncClick: function() {
this.async(function() {
this.click();
}, 1);
},
// any of these changes are considered a change to button state
_pressedChanged: function(pressed) {
this._changedButtonState();
},
_ariaActiveAttributeChanged: function(value, oldValue) {
if (oldValue && oldValue != value && this.hasAttribute(oldValue)) {
this.removeAttribute(oldValue);
}
},
_activeChanged: function(active, ariaActiveAttribute) {
if (this.toggles) {
this.setAttribute(this.ariaActiveAttribute,
active ? 'true' : 'false');
} else {
this.removeAttribute(this.ariaActiveAttribute);
}
this._changedButtonState();
},
_controlStateChanged: function() {
if (this.disabled) {
this._setPressed(false);
} else {
this._changedButtonState();
}
},
// provide hook for follow-on behaviors to react to button-state
_changedButtonState: function() {
if (this._buttonStateChanged) {
this._buttonStateChanged(); // abstract
}
}
};
/** @polymerBehavior */
Polymer.IronButtonState = [
Polymer.IronA11yKeysBehavior,
Polymer.IronButtonStateImpl
]; |
modules/plugins/shared/__tests__/FigCaption-test.js | devrieda/arc-reactor | import React from 'react';
import TestUtils from 'react-addons-test-utils';
import FigCaption from '../FigCaption';
const findByClass = TestUtils.findRenderedDOMComponentWithClass;
const render = TestUtils.renderIntoDocument;
describe('FigCaption', () => {
it('should render', () => {
const text = '';
const figSelected = false;
const caption = render(
<FigCaption text={text} figSelected={figSelected} />
);
const captionComponent = findByClass(caption, 'arc-Editor-FigCaption');
expect(captionComponent).to.exist;
});
});
|
blueprints/route/files/src/routes/__name__/components/__name__.js | IndyXTechFellowship/Cultural-Trail-Web | import React from 'react'
import classes from './<%= pascalEntityName %>.scss'
export const <%= pascalEntityName %> = () => (
<div className={classes['<%= pascalEntityName %>']}>
<h4><%= pascalEntityName %></h4>
</div>
)
export default <%= pascalEntityName %>
|
sites/all/libraries/superfish/sfsmallscreen.js | testevez/wolters-kluwer | /*
* sf-Smallscreen v1.0b - Provides small-screen compatibility for the jQuery Superfish plugin.
*
* Developer's note:
* Built as a part of the Superfish project for Drupal (http://drupal.org/project/superfish)
* Found any bug? have any cool ideas? contact me right away! http://drupal.org/user/619294/contact
*
* jQuery version: 1.3.x or higher.
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($){
$.fn.sfsmallscreen = function(options){
options = $.extend({
mode: 'inactive',
breakpoint: 768,
useragent: '',
title: '',
addSelected: true,
menuClasses: true,
hyperlinkClasses: true,
excludeClass_menu: '',
excludeClass_hyperlink: '',
includeClass_menu: '',
includeClass_hyperlink: ''
}, options);
// We need to clean up the menu from anything unnecessary.
function refine(menu){
if ($('.sf-megamenu', menu).length > 0){
var refined = menu.clone();
refined.find('div.sf-megamenu-column > ol').each(function(){
$(this).replaceWith('<ul>' + $(this).html() + '</ul>');
});
refined.find('div.sf-megamenu-column').each(function(){
$(this).replaceWith($(this).html());
}).end().find('.sf-megamenu-wrapper > ol').each(function(){
$(this).replaceWith($(this).html());
}).end().find('li.sf-megamenu-wrapper').each(function(){
$(this).replaceWith($(this).html());
});
} else {
var refined = menu.clone();
}
refined.find('.sf-smallscreen-remove').each(function(){
$(this).replaceWith($(this).html());
}).end().find('.sf-sub-indicator, .sf-description').each(function(){
$(this).remove();
});
return refined;
}
// Currently the only available reaction is converting the menu into a <select> element;
// In the next version there will be another reaction that will create a "compact" version of
// the menu, using <ul> element hence easy to style with CSS and so on and so forth.
function toSelect(menu, level){
var items = '';
$(menu).children('li').each(function(){
var list = $(this);
list.children('a, span').each(function(){
var item = $(this),
path = item.is('a') ? item.attr('href') : '',
itemClone = item.clone(),
classes = (options.hyperlinkClasses) ? ((options.excludeClass_hyperlink && itemClone.hasClass(options.excludeClass_hyperlink)) ? itemClone.removeClass(options.excludeClass_hyperlink).attr('class') : itemClone.attr('class')) : '',
classes = (options.includeClass_hyperlink && !itemClone.hasClass(options.includeClass_hyperlink)) ? ((options.hyperlinkClasses) ? itemClone.addClass(options.includeClass_hyperlink).attr('class') : options.includeClass_hyperlink) : classes,
classes = (classes) ? ' class="' + classes + '"' : '',
disable = item.is('span') ? ' disabled="disabled"' : '',
subIndicator = 1 < level ? Array(level).join('-') + ' ' : '';
items += '<option value="' + path + '"' + classes + disable + '>' + subIndicator + $.trim(item.text()) +'</option>';
list.find('> ul').each(function(){
items += toSelect(this, level + 1);
});
});
});
return items;
}
// Create the new version, hide the original.
function convert(menu){
var menuClone = menu.clone(), classes = (options.menuClasses) ? ((options.excludeClass_menu && menuClone.hasClass(options.excludeClass_menu)) ? menuClone.removeClass(options.excludeClass_menu).attr('class') : menuClone.attr('class')) : '',
classes = (options.includeClass_menu && !menuClone.hasClass(options.includeClass_menu)) ? ((options.menuClasses) ? menuClone.addClass(options.includeClass_menu).attr('class') : options.includeClass_menu) : classes,
classes = (classes) ? ' class="' + classes + '"' : '';
if ($('#' + menu.attr('id') + '-select').length == 0){
var selectList = $('<select' + classes + ' id="' + menu.attr('id') + '-select"/>'),
refinedMenu = refine(menu);
newMenu = toSelect(refinedMenu, 1);
selectList.append('<option>' + options.title + '</option>').append(newMenu).change(function(){
window.location = selectList.val();
});
if (options.addSelected) {
selectList.find('.active').attr("selected", !0);
}
menu.before(selectList).hide();
}
}
// Turn everything back to normal.
function turnBack(menu){
var id = '#' + menu.attr('id');
$(id + '-select').remove();
$(id).show();
}
// Return original object to support chaining.
return this.each(function(){
var menu = $(this),
mode = options.mode;
// The rest is crystal clear, isn't it? :)
switch (mode){
case 'always_active' :
convert(menu);
break;
case 'window_width' :
if ($(window).width() < options.breakpoint){
convert(menu);
}
var timer;
$(window).resize(function(){
clearTimeout(timer);
timer = setTimeout(function(){
if ($(window).width() < options.breakpoint){
convert(menu);
}
else {
turnBack(menu);
}
}, 100);
});
break;
case 'useragent_custom' :
if (options.useragent != ''){
if (navigator.userAgent.match(options.useragents)){
convert(menu);
}
}
break;
case 'useragent_predefined' :
if (navigator.userAgent.match(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i)){
convert(menu);
}
break;
}
});
};
})(jQuery); |
ajax/libs/react/0.11.0-rc1/react.min.js | kartikrao31/cdnjs | /**
* React v0.11.0-rc1
*
* 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.
*/
!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);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.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("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":104}],2:[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,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;a=String.fromCharCode(u);break;case d.topTextInput:if(a=o.data,a===p)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":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./SyntheticInputEvent":84,"./keyOf":125}],3:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={columnCount:!0,fillOpacity:!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},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},{}],4:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./dangerousStyleValue"),o=e("./hyphenateStyleName"),i=e("./memoizeStringOnly"),a=i(function(e){return o(e)}),s={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];null!=o&&(t+=a(n)+":",t+=r(n,o)+";")}return t||null},setValueForStyles:function(e,t){var o=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=r(i,t[i]);if(a)o[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)o[u]="";else o[i]=""}}}};t.exports=s},{"./CSSProperty":3,"./dangerousStyleValue":99,"./hyphenateStyleName":116,"./memoizeStringOnly":127}],5:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),o=e("./invariant"),i=e("./mixInto");i(n,{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){o(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},{"./PooledClass":26,"./invariant":118,"./mixInto":131}],6:[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,_,e);C.accumulateTwoPhaseDispatches(t),R.batchedUpdates(o,t)}function o(e){y.enqueueEvents(e),y.processEventQueue()}function i(e,t){I=e,_=t,I.attachEvent("onchange",r)}function a(){I&&(I.detachEvent("onchange",r),I=null,_=null)}function s(e,t,n){return e===O.topChange?n:void 0}function u(e,t,n){e===O.topFocus?(a(),i(t,n)):e===O.topBlur&&a()}function c(e,t){I=e,_=t,T=e.value,N=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",A),I.attachEvent("onpropertychange",p)}function l(){I&&(delete I.value,I.detachEvent("onpropertychange",p),I=null,_=null,T=null,N=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==T&&(T=t,r(e))}}function d(e,t,n){return e===O.topInput?n:void 0}function f(e,t,n){e===O.topFocus?(l(),c(t,n)):e===O.topBlur&&l()}function h(e){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!I||I.value===T?void 0:(T=I.value,_)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function m(e,t,n){return e===O.topClick?n:void 0}var g=e("./EventConstants"),y=e("./EventPluginHub"),C=e("./EventPropagators"),E=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),D=e("./isEventSupported"),x=e("./isTextInputElement"),b=e("./keyOf"),O=g.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:b({onChange:null}),captured:b({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},I=null,_=null,T=null,N=null,w=!1;E.canUseDOM&&(w=D("change")&&(!("documentMode"in document)||document.documentMode>8));var S=!1;E.canUseDOM&&(S=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return N.get.call(this)},set:function(e){T=""+e,N.set.call(this,e)}},k={eventTypes:P,extractEvents:function(e,t,r,o){var i,a;if(n(t)?w?i=s:a=u:x(t)?S?i=d:(i=h,a=f):v(t)&&(i=m),i){var c=i(e,t,r);if(c){var l=M.getPooled(P.change,c,o);return C.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,r)}};t.exports=k},{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":74,"./SyntheticEvent":82,"./isEventSupported":119,"./isTextInputElement":121,"./keyOf":125}],7:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],8:[function(e,t){"use strict";function n(e){switch(e){case g.topCompositionStart:return C.compositionStart;case g.topCompositionEnd:return C.compositionEnd;case g.topCompositionUpdate:return C.compositionUpdate}}function r(e,t){return e===g.topKeyDown&&t.keyCode===h}function o(e,t){switch(e){case g.topKeyUp:return-1!==f.indexOf(t.keyCode);case g.topKeyDown:return t.keyCode!==h;case g.topKeyPress:case g.topMouseDown:case g.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,v=u.canUseDOM&&"CompositionEvent"in window,m=!v||"documentMode"in document&&document.documentMode>8&&document.documentMode<=11,g=a.topLevelTypes,y=null,C={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[g.topBlur,g.topCompositionEnd,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[g.topBlur,g.topCompositionStart,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[g.topBlur,g.topCompositionUpdate,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.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 E={eventTypes:C,extractEvents:function(e,t,a,u){var c,p;if(v?c=n(e):y?o(e,u)&&(c=C.compositionEnd):r(e,u)&&(c=C.compositionStart),m&&(y||c!==C.compositionStart?c===C.compositionEnd&&y&&(p=y.getData(),y=null):y=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=E},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":56,"./SyntheticCompositionEvent":80,"./getTextContentAccessor":113,"./keyOf":125}],9:[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 v=0;v<c.length;v++)c[v].parentNode.removeChild(c[v]);for(var m=0;a=e[m];m++)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":12,"./ReactMultiChildUpdateTypes":61,"./getTextContentAccessor":113,"./invariant":118}],10:[function(e,t){"use strict";var n=e("./invariant"),r={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||{},o=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&i._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){n(!i.isStandardName.hasOwnProperty(u)),i.isStandardName[u]=!0;var c=u.toLowerCase();if(i.getPossibleStandardName[c]=u,o.hasOwnProperty(u)){var l=o[u];i.getPossibleStandardName[l]=u,i.getAttributeName[u]=l}else i.getAttributeName[u]=c;i.getPropertyName[u]=a.hasOwnProperty(u)?a[u]:u,i.getMutationMethod[u]=s.hasOwnProperty(u)?s[u]:null;var p=t[u];i.mustUseAttribute[u]=p&r.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=p&r.MUST_USE_PROPERTY,i.hasSideEffects[u]=p&r.HAS_SIDE_EFFECTS,i.hasBooleanValue[u]=p&r.HAS_BOOLEAN_VALUE,i.hasNumericValue[u]=p&r.HAS_NUMERIC_VALUE,i.hasPositiveNumericValue[u]=p&r.HAS_POSITIVE_NUMERIC_VALUE,i.hasOverloadedBooleanValue[u]=p&r.HAS_OVERLOADED_BOOLEAN_VALUE,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u]),n(!!i.hasBooleanValue[u]+!!i.hasNumericValue[u]+!!i.hasOverloadedBooleanValue[u]<=1)}}},o={},i={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<i._isCustomAttributeFunctions.length;t++){var n=i._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=o[e];return r||(o[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:r};t.exports=i},{"./invariant":118}],11:[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":10,"./escapeTextForBrowser":102,"./memoizeStringOnly":127,"./warning":139}],12:[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 v in h)if(h.hasOwnProperty(v)){var m=h[v];h[v]=m.replace(u,"$1 "+c+'="'+v+'" ')}var g=o(h.join(""),i);for(p=0;p<g.length;++p){var y=g[p];y.hasAttribute&&y.hasAttribute(c)&&(v=+y.getAttribute(c),y.removeAttribute(c),s(!d.hasOwnProperty(v)),d[v]=y,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":21,"./createNodesFromMarkup":98,"./emptyFunction":100,"./getMarkupWrap":110,"./invariant":118}],13:[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":125}],14:[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 v=f?i.getID(f):"",m=h?i.getID(h):"",g=o.getPooled(c.mouseLeave,v,a);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=o.getPooled(c.mouseEnter,m,a);return y.type="mouseenter",y.target=h,y.relatedTarget=f,r.accumulateEnterLeaveDispatches(g,y,v,m),l[0]=g,l[1]=y,l}};t.exports=p},{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":59,"./SyntheticMouseEvent":86,"./keyOf":125}],15:[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":124}],16:[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":100}],17:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),r=e("./EventPluginUtils"),o=e("./accumulate"),i=e("./forEachAccumulated"),a=e("./invariant"),s=(e("./isEventSupported"),e("./monitorCodeUse"),{}),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":18,"./EventPluginUtils":19,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118,"./isEventSupported":119,"./monitorCodeUse":132}],18:[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":118}],19:[function(e,t){"use strict";function n(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function r(e){return e===v.topMouseMove||e===v.topTouchMove}function o(e){return e===v.topMouseDown||e===v.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}},v=d.topLevelTypes,m={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:l,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=m},{"./EventConstants":15,"./invariant":118}],20:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(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=v(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("./accumulate"),f=e("./forEachAccumulated"),h=l.PropagationPhases,v=p.getListener,m={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=m},{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":92,"./forEachAccumulated":105}],21:[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},{}],22:[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,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,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,formNoValidate:s,frameBorder:i,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:null,loop:a|s,max:null,maxLength:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,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,scrollLeft:a,scrolling:null,scrollTop:a,seamless:i|s,selected:a|s,shape:null,size:i|l,span:l,spellCheck:null,src:null,srcDoc:a,srcSet:null,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:{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":10,"./ExecutionEnvironment":21}],23:[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":67,"./invariant":118}],24:[function(e,t){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),o=e("./accumulate"),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":29,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118}],25:[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":15,"./emptyFunction":100}],26:[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":118}],27:[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("./ReactDescriptor"),l=e("./ReactDOM"),p=e("./ReactDOMComponent"),d=e("./ReactDefaultInjection"),f=e("./ReactInstanceHandles"),h=e("./ReactMount"),v=e("./ReactMultiChild"),m=e("./ReactPerf"),g=e("./ReactPropTypes"),y=e("./ReactServerRendering"),C=e("./ReactTextComponent"),E=e("./onlyChild");d.inject();var R={Children:{map:o.map,forEach:o.forEach,only:E},DOM:l,PropTypes:g,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createDescriptor:function(e){var t=Array.prototype.slice.call(arguments,1);return e.apply(null,t)},constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,renderComponent:m.measure("React","renderComponent",h.renderComponent),renderComponentToString:y.renderComponentToString,renderComponentToStaticMarkup:y.renderComponentToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidClass:c.isValidFactory,isValidComponent:c.isValidDescriptor,withContext:s.withContext,__internals:{Component:i,CurrentOwner:u,DOMComponent:p,DOMPropertyOperations:n,InstanceHandles:f,Mount:h,MultiChild:v,TextComponent:C}};R.version="0.11.0-rc1",t.exports=R},{"./DOMPropertyOperations":11,"./EventPluginUtils":19,"./ReactChildren":30,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./ReactPropTypes":67,"./ReactServerRendering":71,"./ReactTextComponent":73,"./onlyChild":133}],28:[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":51,"./ReactMount":59,"./invariant":118}],29:[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("./isEventSupported"),c=e("./merge"),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),v=c(a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e
}},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],c=r.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];a.hasOwnProperty(d)&&a[d]||(d===c.topWheel?u("wheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"wheel",o):u("mousewheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"mousewheel",o):v.ReactEventListener.trapBubbledEvent(c.topWheel,"DOMMouseScroll",o):d===c.topScroll?u("scroll",!0)?v.ReactEventListener.trapCapturedEvent(c.topScroll,"scroll",o):v.ReactEventListener.trapBubbledEvent(c.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):d===c.topFocus||d===c.topBlur?(u("focus",!0)?(v.ReactEventListener.trapCapturedEvent(c.topFocus,"focus",o),v.ReactEventListener.trapCapturedEvent(c.topBlur,"blur",o)):u("focusin")&&(v.ReactEventListener.trapBubbledEvent(c.topFocus,"focusin",o),v.ReactEventListener.trapBubbledEvent(c.topBlur,"focusout",o)),a[c.topBlur]=!0,a[c.topFocus]=!0):f.hasOwnProperty(d)&&v.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;v.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=v},{"./EventConstants":15,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ReactEventEmitterMixin":53,"./ViewportMetrics":91,"./isEventSupported":119,"./merge":128}],30:[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":26,"./traverseAllChildren":138,"./warning":139}],31:[function(e,t){"use strict";var n=e("./ReactDescriptor"),r=e("./ReactOwner"),o=e("./ReactUpdates"),i=e("./invariant"),a=e("./keyMirror"),s=e("./merge"),u=a({MOUNTED:null,UNMOUNTED:null}),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){i(!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._pendingDescriptor||this._descriptor;this.replaceProps(s(n.props,e),t)},replaceProps:function(e,t){i(this.isMounted()),i(0===this._mountDepth),this._pendingDescriptor=n.cloneAndReplaceProps(this._pendingDescriptor||this._descriptor,e),o.enqueueUpdate(this,t)},_setPropsInternal:function(e,t){var r=this._pendingDescriptor||this._descriptor;this._pendingDescriptor=n.cloneAndReplaceProps(r,s(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._descriptor=e,this._pendingDescriptor=null},mountComponent:function(e,t,n){i(!this.isMounted());var o=this._descriptor.props;if(null!=o.ref){var a=this._descriptor._owner;r.addComponentAsRefTo(this,o.ref,a)}this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){i(this.isMounted());var e=this.props;null!=e.ref&&r.removeComponentAsRefFrom(this,e.ref,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){i(this.isMounted()),this._pendingDescriptor=e,this.performUpdateIfNecessary(t)},performUpdateIfNecessary:function(e){if(null!=this._pendingDescriptor){var t=this._descriptor,n=this._pendingDescriptor;this._descriptor=n,this.props=n.props,this._owner=n._owner,this._pendingDescriptor=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this._descriptor;(n._owner!==t._owner||n.props.ref!==t.props.ref)&&(null!=t.props.ref&&r.removeComponentAsRefFrom(this,t.props.ref,t._owner),null!=n.props.ref&&r.addComponentAsRefTo(this,n.props.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},{"./ReactDescriptor":49,"./ReactOwner":62,"./ReactUpdates":74,"./invariant":118,"./keyMirror":124,"./merge":128}],32:[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":40,"./ReactMarkupChecksum":58,"./ReactMount":59,"./ReactPerf":63,"./ReactReconcileTransaction":69,"./getReactRootElementInContainer":112,"./invariant":118,"./setInnerHTML":134}],33:[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=N.hasOwnProperty(t)?N[t]:null;A.hasOwnProperty(t)&&D(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&D(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function i(e){var t=e._compositeLifeCycleState;D(e.isMounted()||t===S.MOUNTING),D(t!==S.RECEIVING_STATE),D(t!==S.UNMOUNTING)}function a(e,t){D(!h.isValidFactory(t)),D(!h.isValidDescriptor(t));var n=e.prototype;for(var r in t){var i=t[r];if(t.hasOwnProperty(r))if(o(n,r),w.hasOwnProperty(r))w[r](e,i);else{var a=N.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=N[r];D(a&&(f===_.DEFINE_MANY_MERGED||f===_.DEFINE_MANY)),f===_.DEFINE_MANY_MERGED?n[r]=c(n[r],i):f===_.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 e,i=r;if(o){var a=e[n],s=typeof a,u=typeof r;D("function"===s&&"function"===u),i=l(a,r)}e[n]=i}}}function u(e,t){return D(e&&t&&"object"==typeof e&&"object"==typeof t),P(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("./ReactDescriptor"),v=(e("./ReactDescriptorValidator"),e("./ReactEmptyComponent")),m=e("./ReactErrorUtils"),g=e("./ReactOwner"),y=e("./ReactPerf"),C=e("./ReactPropTransferer"),E=e("./ReactPropTypeLocations"),R=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),M=e("./instantiateReactComponent"),D=e("./invariant"),x=e("./keyMirror"),b=e("./merge"),O=e("./mixInto"),P=(e("./monitorCodeUse"),e("./mapObject")),I=e("./shouldUpdateReactComponent"),_=(e("./warning"),x({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null})),T=[],N={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},w={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,E.childContext),e.childContextTypes=b(e.childContextTypes,t)},contextTypes:function(e,t){r(e,t,E.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,E.prop),e.propTypes=b(e.propTypes,t)},statics:function(e,t){s(e,t)}},S=x({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),A={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!==S.MOUNTING},mountComponent:y.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=S.MOUNTING,this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.context=this._processContext(this._descriptor._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=M(this._renderValidatedComponent()),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=S.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,R.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){var t,n=this.constructor.defaultProps;if(n){t=b(e);for(var r in n)"undefined"==typeof t[r]&&(t[r]=n[r])}else t=e;return t},_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!==S.MOUNTING&&t!==S.RECEIVING_PROPS&&(null!=this._pendingDescriptor||null!=this._pendingState||this._pendingForceUpdate)){var n=this.context,r=this.props,o=this._descriptor;null!=this._pendingDescriptor&&(o=this._pendingDescriptor,n=this._processContext(o._context),r=this._processProps(o.props),this._pendingDescriptor=null,this._compositeLifeCycleState=S.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(r,n)),this._compositeLifeCycleState=S.RECEIVING_STATE;var i=this._pendingState||this.state;this._pendingState=null;try{var a=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(r,i,n);a?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,n,e)):(this._descriptor=o,this.props=r,this.state=i,this.context=n,this._owner=o._owner)}finally{this._compositeLifeCycleState=null}}},_performComponentUpdate:function(e,t,n,r,o){var i=this._descriptor,a=this.props,s=this.state,u=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this._descriptor=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._descriptor||null==e._owner)&&p.Mixin.receiveComponent.call(this,e,t)},updateComponent:y.measure("ReactCompositeComponent","updateComponent",function(e,t){p.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=n._descriptor,o=this._renderValidatedComponent();if(I(r,o))n.receiveComponent(o,e);else{var i=this._rootNodeID,a=n._rootNodeID;n.unmountComponent(),this._renderedComponent=M(o);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===S.MOUNTING),D(t!==S.RECEIVING_STATE&&t!==S.UNMOUNTING),this._pendingForceUpdate=!0,R.enqueueUpdate(this,e)},_renderValidatedComponent:y.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._descriptor._context),f.current=this;try{e=this.render(),null===e||e===!1?(e=v.getEmptyComponent(),v.registerNullComponentID(this._rootNodeID)):v.deregisterNullComponentID(this._rootNodeID)}finally{d.current=t,f.current=null}return D(h.isValidDescriptor(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(m.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=function(){return e.apply(t,arguments)};return n}},k=function(){};O(k,p.Mixin),O(k,g.Mixin),O(k,C.Mixin),O(k,A);var U={LifeCycle:S,Base:k,createClass:function(e){var t=function(e,t){this.construct(e,t)};t.prototype=new k,t.prototype.constructor=t,T.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),D(t.prototype.render);for(var n in N)t.prototype[n]||(t.prototype[n]=null);var r=h.createFactory(t);return r},injection:{injectMixin:function(e){T.push(e)}}};t.exports=U},{"./ReactComponent":31,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./ReactEmptyComponent":51,"./ReactErrorUtils":52,"./ReactOwner":62,"./ReactPerf":63,"./ReactPropTransferer":64,"./ReactPropTypeLocationNames":65,"./ReactPropTypeLocations":66,"./ReactUpdates":74,"./instantiateReactComponent":117,"./invariant":118,"./keyMirror":124,"./mapObject":126,"./merge":128,"./mixInto":131,"./monitorCodeUse":132,"./shouldUpdateReactComponent":136,"./warning":139}],34:[function(e,t){"use strict";var n=e("./merge"),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},{"./merge":128}],35:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],36:[function(e,t){"use strict";function n(e,t){var n=function(e){this.construct(e)};n.prototype=new o(t,e),n.prototype.constructor=n,n.displayName=t;var i=r.createFactory(n);return i}var r=e("./ReactDescriptor"),o=(e("./ReactDescriptorValidator"),e("./ReactDOMComponent")),i=e("./mergeInto"),a=e("./mapObject"),s=a({a:!1,abbr:!1,address:!1,area:!0,article:!1,aside:!1,audio:!1,b:!1,base:!0,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!0,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!0,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!0,circle:!1,defs:!1,ellipse:!1,g:!1,line:!1,linearGradient:!1,mask:!1,path:!1,pattern:!1,polygon:!1,polyline:!1,radialGradient:!1,rect:!1,stop:!1,svg:!1,text:!1,tspan:!1},n),u={injectComponentClasses:function(e){i(s,e)}};s.injection=u,t.exports=s},{"./ReactDOMComponent":38,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./mapObject":126,"./mergeInto":130}],37:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),i=e("./ReactDOM"),a=e("./keyMirror"),s=i.button,u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=o.createClass({displayName:"ReactDOMButton",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&u[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":124}],38:[function(e,t){"use strict";function n(e){e&&(v(null==e.children||null==e.dangerouslySetInnerHTML),v(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=p.findReactContainerForID(e);if(o){var i=o.nodeType===x?o.ownerDocument:o;E(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e,t){this._tagOpen="<"+e,this._tagClose=t?"":"</"+e+">",this.tagName=e.toUpperCase()}var i=e("./CSSPropertyOperations"),a=e("./DOMProperty"),s=e("./DOMPropertyOperations"),u=e("./ReactBrowserComponentMixin"),c=e("./ReactComponent"),l=e("./ReactBrowserEventEmitter"),p=e("./ReactMount"),d=e("./ReactMultiChild"),f=e("./ReactPerf"),h=e("./escapeTextForBrowser"),v=e("./invariant"),m=e("./keyOf"),g=e("./merge"),y=e("./mixInto"),C=l.deleteListener,E=l.listenTo,R=l.registrationNameModules,M={string:!0,number:!0},D=m({style:null}),x=1;o.Mixin={mountComponent:f.measure("ReactDOMComponent","mountComponent",function(e,t,r){return c.Mixin.mountComponent.call(this,e,t,r),n(this.props),this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+this._tagClose}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n=this._tagOpen;for(var o in t)if(t.hasOwnProperty(o)){var a=t[o];if(null!=a)if(R.hasOwnProperty(o))r(this._rootNodeID,o,a,e);else{o===D&&(a&&(a=t.style=g(t.style)),a=i.createMarkupForStyles(a));var u=s.createMarkupForProperty(o,a);u&&(n+=" "+u)}}if(e.renderToStaticMarkup)return n+">";var c=s.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 h(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._descriptor||null==e._owner)&&c.Mixin.receiveComponent.call(this,e,t)},updateComponent:f.measure("ReactDOMComponent","updateComponent",function(e,t){n(this._descriptor.props),c.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,o,i,s=this.props;for(n in e)if(!s.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===D){var u=e[n];for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else R.hasOwnProperty(n)?C(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in s){var l=s[n],p=e[n];if(s.hasOwnProperty(n)&&l!==p)if(n===D)if(l&&(l=s.style=g(l)),p){for(o in p)!p.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in l)l.hasOwnProperty(o)&&p[o]!==l[o]&&(i=i||{},i[o]=l[o])}else i=l;else R.hasOwnProperty(n)?r(this._rootNodeID,n,l,t):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,l)}i&&c.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,l=null!=r||null!=i,p=null!=o||null!=a;null!=s&&null==u?this.updateChildren(null,t):l&&!p&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&c.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.Mixin.unmountComponent.call(this)}},y(o,c.Mixin),y(o,o.Mixin),y(o,d.Mixin),y(o,u),t.exports=o},{"./CSSPropertyOperations":4,"./DOMProperty":10,"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./escapeTextForBrowser":102,"./invariant":118,"./keyOf":125,"./merge":128,"./mixInto":131}],39:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.form,u=i.createClass({displayName:"ReactDOMForm",mixins:[o,r],render:function(){return this.transferPropsTo(s(null,this.props.children))},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],40:[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":4,"./DOMChildrenOperations":9,"./DOMPropertyOperations":11,"./ReactMount":59,"./ReactPerf":63,"./invariant":118,"./setInnerHTML":134}],41:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.img,u=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],42:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./ReactMount"),c=e("./invariant"),l=e("./merge"),p=s.input,d={},f=a.createClass({displayName:"ReactDOMInput",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue;return{checked:this.props.defaultChecked||!1,value:null!=e?e:null}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=l(this.props);e.defaultChecked=null,e.defaultValue=null;var t=o.getValue(this);e.value=null!=t?t:this.state.value;var n=o.getChecked(this);return e.checked=null!=n?n:this.state.checked,e.onChange=this._handleChange,p(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());d[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete d[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&r.setValueForProperty(e,"checked",this.props.checked||!1);var t=o.getValue(this);null!=t&&r.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,n=o.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({checked:e.target.checked,value:e.target.value});var r=this.props.name;if("radio"===this.props.type&&null!=r){for(var i=this.getDOMNode(),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+r)+'][type="radio"]'),l=0,p=s.length;p>l;l++){var f=s[l];if(f!==i&&f.form===i.form){var h=u.getID(f);c(h);var v=d[h];c(v),v.setState({checked:!1})}}}return t}});t.exports=f},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":59,"./invariant":118,"./merge":128}],43:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),o=e("./ReactDOM"),i=(e("./warning"),o.option),a=r.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});t.exports=a},{"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./warning":139}],44:[function(e,t){"use strict";function n(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 r(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 o=e("./AutoFocusMixin"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactDOM"),c=e("./merge"),l=u.select,p=s.createClass({displayName:"ReactDOMSelect",mixins:[o,i.Mixin,a],propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},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]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return e.onChange=this._handleChange,e.value=null,l(e,this.props.children)},componentDidMount:function(){r(this,i.getValue(this))},componentDidUpdate:function(e){var t=i.getValue(this),n=!!e.multiple,o=!!this.props.multiple;(null!=t||n!==o)&&r(this,t)},_handleChange:function(e){var t,n=i.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1);var r;if(this.props.multiple){r=[];for(var o=e.target.options,a=0,s=o.length;s>a;a++)o[a].selected&&r.push(o[a].value)}else r=e.target.value;return this.setState({value:r}),t}});t.exports=p},{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./merge":128}],45:[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();if(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 v=h.collapsed;return h.detach(),{start:v?f:d,end:v?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){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)),p.detach()}}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":21,"./getNodeForCharacterOffset":111,"./getTextContentAccessor":113}],46:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./invariant"),c=e("./merge"),l=(e("./warning"),s.textarea),p=a.createClass({displayName:"ReactDOMTextarea",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(u(null==e),Array.isArray(t)&&(u(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=o.getValue(this);return{initialValue:""+(null!=n?n:e)}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return u(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,l(e,this.state.initialValue)},componentDidUpdate:function(){var e=o.getValue(this);
if(null!=e){var t=this.getDOMNode();r.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,n=o.getOnChange(this);return n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({value:e.target.value}),t}});t.exports=p},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":118,"./merge":128,"./warning":139}],47:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),o=e("./Transaction"),i=e("./emptyFunction"),a=e("./mixInto"),s={initialize:i,close:function(){p.isBatchingUpdates=!1}},u={initialize:i,close:r.flushBatchedUpdates.bind(r)},c=[u,s];a(n,o.Mixin),a(n,{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},{"./ReactUpdates":74,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],48:[function(e,t){"use strict";function n(){x.EventEmitter.injectReactEventListener(D),x.EventPluginHub.injectEventPluginOrder(s),x.EventPluginHub.injectInstanceHandle(b),x.EventPluginHub.injectMount(O),x.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:_,EnterLeaveEventPlugin:u,ChangeEventPlugin:o,CompositionEventPlugin:a,MobileSafariClickEventPlugin:p,SelectEventPlugin:P,BeforeInputEventPlugin:r}),x.DOM.injectComponentClasses({button:m,form:g,img:y,input:C,option:E,select:R,textarea:M,html:N(v.html),head:N(v.head),body:N(v.body)}),x.CompositeComponent.injectMixin(d),x.DOMProperty.injectDOMPropertyConfig(l),x.DOMProperty.injectDOMPropertyConfig(T),x.EmptyComponent.injectEmptyComponent(v.noscript),x.Updates.injectReconcileTransaction(f.ReactReconcileTransaction),x.Updates.injectBatchingStrategy(h),x.RootIndex.injectCreateReactRootIndex(c.canUseDOM?i.createReactRootIndex:I.createReactRootIndex),x.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"),v=e("./ReactDOM"),m=e("./ReactDOMButton"),g=e("./ReactDOMForm"),y=e("./ReactDOMImg"),C=e("./ReactDOMInput"),E=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),D=e("./ReactEventListener"),x=e("./ReactInjection"),b=e("./ReactInstanceHandles"),O=e("./ReactMount"),P=e("./SelectEventPlugin"),I=e("./ServerReactRootIndex"),_=e("./SimpleEventPlugin"),T=e("./SVGDOMPropertyConfig"),N=e("./createFullPageComponent");t.exports={inject:n}},{"./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,"./ReactEventListener":54,"./ReactInjection":55,"./ReactInstanceHandles":57,"./ReactMount":59,"./SVGDOMPropertyConfig":75,"./SelectEventPlugin":76,"./ServerReactRootIndex":77,"./SimpleEventPlugin":78,"./createFullPageComponent":97}],49:[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];e[n]="function"==typeof r?r.bind(t):r}}var r=e("./ReactContext"),o=e("./ReactCurrentOwner"),i=e("./merge"),a=(e("./warning"),function(){});a.createFactory=function(e){var t=Object.create(a.prototype),s=function(e,n){null==e?e={}:"object"==typeof e&&(e=i(e));var a=arguments.length-1;if(1===a)e.children=n;else if(a>1){for(var s=Array(a),u=0;a>u;u++)s[u]=arguments[u+1];e.children=s}var c=Object.create(t);return c._owner=o.current,c._context=r.current,c.props=e,c};return s.prototype=t,s.type=e,t.type=e,n(s,e),t.constructor=s,s},a.cloneAndReplaceProps=function(e,t){var n=Object.create(e.constructor.prototype);return n._owner=e._owner,n._context=e._context,n.props=t,n},a.isValidFactory=function(e){return"function"==typeof e&&e.prototype instanceof a},a.isValidDescriptor=function(e){return e instanceof a},t.exports=a},{"./ReactContext":34,"./ReactCurrentOwner":35,"./merge":128,"./warning":139}],50:[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.props.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){m.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.isValidDescriptor(i)&&r(i,t)}else if(c.isValidDescriptor(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 v)&&(v[i.message]=!0,d("react_failed_descriptor_type_check",{message:i.message}))}}var c=e("./ReactDescriptor"),l=e("./ReactPropTypeLocations"),p=e("./ReactCurrentOwner"),d=e("./monitorCodeUse"),f={react_key_warning:{},react_numeric_key_warning:{}},h={},v={},m=/^\d+$/,g={createFactory:function(e,t,n){var r=function(){for(var r=e.apply(this,arguments),o=1;o<arguments.length;o++)s(arguments[o],r.type);var i=r.type.displayName;return t&&u(i,t,r.props,l.prop),n&&u(i,n,r._context,l.context),r};r.prototype=e.prototype,r.type=e.type;for(var o in e)e.hasOwnProperty(o)&&(r[o]=e[o]);return r}};t.exports=g},{"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactPropTypeLocations":66,"./monitorCodeUse":132}],51:[function(e,t){"use strict";function n(){return s(a),a()}function r(e){u[e]=!0}function o(e){delete u[e]}function i(e){return u[e]}var a,s=e("./invariant"),u={},c={injectEmptyComponent:function(e){a=e}},l={deregisterNullComponentID:o,getEmptyComponent:n,injection:c,isNullComponentID:i,registerNullComponentID:r};t.exports=l},{"./invariant":118}],52:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],53:[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":17}],54:[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(d(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)||"";v._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=f(window);e(t)}var a=e("./EventListener"),s=e("./ExecutionEnvironment"),u=e("./PooledClass"),c=e("./ReactInstanceHandles"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./getEventTarget"),f=e("./getUnboundedScrollPosition"),h=e("./mixInto");h(r,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,v.dispatchEvent.bind(null,e)):void 0},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,v.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(v._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=v},{"./EventListener":16,"./ExecutionEnvironment":21,"./PooledClass":26,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactUpdates":74,"./getEventTarget":109,"./getUnboundedScrollPosition":114,"./mixInto":131}],55:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),o=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=e("./ReactEmptyComponent"),u=e("./ReactBrowserEventEmitter"),c=e("./ReactPerf"),l=e("./ReactRootIndex"),p=e("./ReactUpdates"),d={Component:o.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EmptyComponent:s.injection,EventPluginHub:r.injection,DOM:a.injection,EventEmitter:u.injection,Perf:c.injection,RootIndex:l.injection,Updates:p.injection};t.exports=d},{"./DOMProperty":10,"./EventPluginHub":17,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEmptyComponent":51,"./ReactPerf":63,"./ReactRootIndex":70,"./ReactUpdates":74}],56:[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":45,"./containsNode":94,"./focusNode":104,"./getActiveElement":106}],57:[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 v;if(o&&f===e||u&&f===t||(v=n(f,c,r)),v===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,v={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=v},{"./ReactRootIndex":70,"./invariant":118}],58:[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":93}],59:[function(e,t){"use strict";function n(e){var t=g(e);return t&&T.getID(t)}function r(e){var t=o(e);if(t)if(D.hasOwnProperty(t)){var n=D[t];n!==e&&(C(!s(n,t)),D[t]=e)}else D[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(M)||""}function i(e,t){var n=o(e);n!==t&&delete D[n],e.setAttribute(M,t),D[t]=e}function a(e){return D.hasOwnProperty(e)&&s(D[e],e)||(D[e]=T.findReactNodeByID(e)),D[e]}function s(e,t){if(e){C(o(e)===t);var n=T.findReactContainerForID(t);if(n&&m(n,e))return!0}return!1}function u(e){delete D[e]}function c(e){var t=D[e];return t&&s(t,e)?void(_=t):!1}function l(e){_=null,h.traverseAncestors(e,c);var t=_;return _=null,t}var p=e("./DOMProperty"),d=e("./ReactBrowserEventEmitter"),f=(e("./ReactCurrentOwner"),e("./ReactDescriptor")),h=e("./ReactInstanceHandles"),v=e("./ReactPerf"),m=e("./containsNode"),g=e("./getReactRootElementInContainer"),y=e("./instantiateReactComponent"),C=e("./invariant"),E=e("./shouldUpdateReactComponent"),R=(e("./warning"),h.SEPARATOR),M=p.ID_ATTRIBUTE_NAME,D={},x=1,b=9,O={},P={},I=[],_=null,T={_instancesByReactRootID:O,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){var o=t.props;return T.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){C(t&&(t.nodeType===x||t.nodeType===b)),d.ensureScrollValueMonitoring();var n=T.registerContainer(t);return O[n]=e,n},_renderNewRootComponent:v.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var r=y(e),o=T._registerComponent(r,t);return r.mountComponentIntoNode(o,t,n),r}),renderComponent:function(e,t,r){C(f.isValidDescriptor(e));var o=O[n(t)];if(o){var i=o._descriptor;if(E(i,e))return T._updateRootComponent(o,e,t,r);T.unmountComponentAtNode(t)}var a=g(t),s=a&&T.isRenderedByReact(a),u=s&&!o,c=T._renderNewRootComponent(e,t,u);return r&&r.call(c),c},constructAndRenderComponent:function(e,t,n){return T.renderComponent(e(t),n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return C(r),T.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=n(e);return t&&(t=h.getReactRootIDFromNodeID(t)),t||(t=h.createReactRootID()),P[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),r=O[t];return r?(T.unmountComponentFromNode(r,e),delete O[t],delete P[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===b&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=h.getReactRootIDFromNodeID(e),n=P[t];return n},findReactNodeByID:function(e){var t=T.findReactContainerForID(e);return T.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=T.getID(e);return t?t.charAt(0)===R:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(T.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=I,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=T.getID(a);s?t===s?i=a:h.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,C(!1)},getReactRootID:n,getID:r,setID:i,getNode:a,purgeID:u};t.exports=T},{"./DOMProperty":10,"./ReactBrowserEventEmitter":29,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactPerf":63,"./containsNode":94,"./getReactRootElementInContainer":112,"./instantiateReactComponent":117,"./invariant":118,"./shouldUpdateReactComponent":136,"./warning":139}],60:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:v.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,v),s())}function s(){h.length=0,v.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],v=[],m={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);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._descriptor,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);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=m},{"./ReactComponent":31,"./ReactMultiChildUpdateTypes":61,"./flattenChildren":103,"./instantiateReactComponent":117,"./shouldUpdateReactComponent":136}],61:[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":124}],62:[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":101,"./invariant":118}],63:[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},{}],64:[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("./emptyFunction"),i=e("./invariant"),a=e("./joinClasses"),s=e("./merge"),u=n(function(e,t){return s(t,e)}),c={children:o,className:n(a),key:o,ref:o,style:u},l={TransferStrategies:c,mergeProps:function(e,t){return r(s(e),t)},Mixin:{transferPropsTo:function(e){return i(e._owner===this),r(e.props,this.props),e}}};t.exports=l},{"./emptyFunction":100,"./invariant":118,"./joinClasses":123,"./merge":128}],65:[function(e,t){"use strict";var n={};t.exports=n},{}],66:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":124}],67:[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=g[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=g[o],u=v(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}}return n(t)}function o(){return n(y.thatReturns())}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=g[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(!m.isValidDescriptor(e[t])){var o=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a React component."))}}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=g[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=g[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=g[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=g[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=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a renderable prop."))}}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=g[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(m.isValidDescriptor(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 v(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var m=e("./ReactDescriptor"),g=e("./ReactPropTypeLocationNames"),y=e("./emptyFunction"),C="<<anonymous>>",E={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,component:a(),instanceOf:s,objectOf:c,oneOf:u,oneOfType:l,renderable:p(),shape:d};t.exports=E},{"./ReactDescriptor":49,"./ReactPropTypeLocationNames":65,"./emptyFunction":100}],68:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),o=e("./ReactBrowserEventEmitter"),i=e("./mixInto");i(n,{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},{"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./mixInto":131}],69:[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("./mixInto"),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],v={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,u.Mixin),c(n,v),o.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./ReactInputSelection":56,"./ReactPutListenerQueue":68,"./Transaction":90,"./mixInto":131}],70:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],71:[function(e,t){"use strict";function n(e){c(o.isValidDescriptor(e)),c(!(2===arguments.length&&"function"==typeof arguments[1]));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=u(e),o=r.mountComponent(n,t,0);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidDescriptor(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=u(e);return r.mountComponent(n,t,0)},null)}finally{s.release(t)}}var o=e("./ReactDescriptor"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderComponentToString:n,renderComponentToStaticMarkup:r}},{"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMarkupChecksum":58,"./ReactServerRenderingTransaction":72,"./instantiateReactComponent":117,"./invariant":118}],72:[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("./emptyFunction"),u=e("./mixInto"),c={initialize:function(){this.reactMountReady.reset()},close:s},l={initialize:function(){this.putListenerQueue.reset()},close:s},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}};u(n,a.Mixin),u(n,d),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactPutListenerQueue":68,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],73:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactComponent"),i=e("./ReactDescriptor"),a=e("./escapeTextForBrowser"),s=e("./mixInto"),u=function(e){this.construct(e)};s(u,o.Mixin),s(u,r),s(u,{mountComponent:function(e,t,r){o.Mixin.mountComponent.call(this,e,t,r);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,o.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}}),t.exports=i.createFactory(u)},{"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactComponent":31,"./ReactDescriptor":49,"./escapeTextForBrowser":102,"./mixInto":131}],74:[function(e,t){"use strict";function n(){d(R.ReactReconcileTransaction&&v)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=u.getPooled(null),this.reconcileTransaction=R.ReactReconcileTransaction.getPooled()}function o(e,t,r){n(),v.batchedUpdates(e,t,r)}function i(e,t){return e._mountDepth-t._mountDepth}function a(e){var t=e.dirtyComponentsLength;d(t===h.length),h.sort(i);for(var n=0;t>n;n++){var r=h[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 d(!t||"function"==typeof t),n(),v.isBatchingUpdates?(h.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):void v.batchedUpdates(s,e,t)}var u=e("./CallbackQueue"),c=e("./PooledClass"),l=(e("./ReactCurrentOwner"),e("./ReactPerf")),p=e("./Transaction"),d=e("./invariant"),f=e("./mixInto"),h=(e("./warning"),[]),v=null,m={initialize:function(){this.dirtyComponentsLength=h.length},close:function(){this.dirtyComponentsLength!==h.length?(h.splice(0,this.dirtyComponentsLength),C()):h.length=0}},g={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},y=[m,g];f(r,p.Mixin),f(r,{getTransactionWrappers:function(){return y},destructor:function(){this.dirtyComponentsLength=null,u.release(this.callbackQueue),this.callbackQueue=null,R.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return p.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),c.addPoolingTo(r);var C=l.measure("ReactUpdates","flushBatchedUpdates",function(){for(;h.length;){var e=r.getPooled();e.perform(a,null,e),r.release(e)}}),E={injectReconcileTransaction:function(e){d(e),R.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){d(e),d("function"==typeof e.batchedUpdates),d("boolean"==typeof e.isBatchingUpdates),v=e}},R={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:C,injection:E};t.exports=R},{"./CallbackQueue":5,"./PooledClass":26,"./ReactCurrentOwner":35,"./ReactPerf":63,"./Transaction":90,"./invariant":118,"./mixInto":131,"./warning":139}],75:[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":10}],76:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(document.selection){var t=document.selection.createRange();return{parentElement:t.parentElement(),text:t.text,top:t.boundingTop,left:t.boundingLeft}}var n=window.getSelection();return{anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}}function r(e){if(!g&&null!=h&&h==u()){var t=n(h);if(!m||!p(m,t)){m=t;var r=s.getPooled(f.select,v,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,v=null,m=null,g=!1,y={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,v=n,m=null);break;case d.topBlur:h=null,v=null,m=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=y},{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":56,"./SyntheticEvent":82,"./getActiveElement":106,"./isTextInputElement":121,"./keyOf":125,"./shallowEqual":135}],77:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],78:[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("./invariant"),v=e("./keyOf"),m=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})}}},y={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 y)y[C].dependencies=[C];var E={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=y[e];if(!v)return null;var g;switch(e){case m.topInput:case m.topLoad:case m.topError:case m.topReset:case m.topSubmit:g=a;break;case m.topKeyPress:if(0===r.charCode)return null;case m.topKeyDown:case m.topKeyUp:g=u;break;case m.topBlur:case m.topFocus:g=s;break;case m.topClick:if(2===r.button)return null;case m.topContextMenu:case m.topDoubleClick:case m.topMouseDown:case m.topMouseMove:case m.topMouseOut:case m.topMouseOver:case m.topMouseUp:g=c;break;case m.topDrag:case m.topDragEnd:case m.topDragEnter:case m.topDragExit:case m.topDragLeave:case m.topDragOver:case m.topDragStart:case m.topDrop:g=l;break;case m.topTouchCancel:case m.topTouchEnd:case m.topTouchMove:case m.topTouchStart:g=p;break;case m.topScroll:g=d;break;case m.topWheel:g=f;break;case m.topCopy:case m.topCut:case m.topPaste:g=i}h(g);var C=g.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(C),C}};t.exports=E},{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":79,"./SyntheticDragEvent":81,"./SyntheticEvent":82,"./SyntheticFocusEvent":83,"./SyntheticKeyboardEvent":85,"./SyntheticMouseEvent":86,"./SyntheticTouchEvent":87,"./SyntheticUIEvent":88,"./SyntheticWheelEvent":89,"./invariant":118,"./keyOf":125}],79:[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":82}],80:[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":82}],81:[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":86}],82:[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 i in r)if(r.hasOwnProperty(i)){var a=r[i];this[i]=a?a(n):n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?o.thatReturnsTrue:o.thatReturnsFalse,this.isPropagationStopped=o.thatReturnsFalse}var r=e("./PooledClass"),o=e("./emptyFunction"),i=e("./getEventTarget"),a=e("./merge"),s=e("./mergeInto"),u={type:null,target:i,currentTarget:o.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=o.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=o.thatReturnsTrue},persist:function(){this.isPersistent=o.thatReturnsTrue},isPersistent:o.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=u,n.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);s(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=a(n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./PooledClass":26,"./emptyFunction":100,"./getEventTarget":109,"./merge":128,"./mergeInto":130}],83:[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":88}],84:[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":82}],85:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventKey"),i=e("./getEventModifierState"),a={key:o,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:i,charCode:function(e){return"keypress"===e.type?"charCode"in e?e.charCode:e.keyCode:0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return e.keyCode||e.charCode}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":88,"./getEventKey":107,"./getEventModifierState":108}],86:[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,getEventModifierState: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":88,"./ViewportMetrics":91,"./getEventModifierState":108}],87:[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":88,"./getEventModifierState":108}],88:[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":82,"./getEventTarget":109}],89:[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":86}],90:[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":118}],91:[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":114}],92:[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?e.concat(t):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":118}],93:[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},{}],94:[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":122}],95:[function(e,t){function n(e,t,n,r,o,i){e=e||{};for(var a,s=[t,n,r,o,i],u=0;s[u];){a=s[u++];for(var c in a)e[c]=a[c];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&e.toString!==a.toString&&(e.toString=a.toString)}return e}t.exports=n},{}],96:[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":137}],97:[function(e,t){"use strict";function n(e){var t=r.createClass({displayName:"ReactFullPageComponent"+(e.type.displayName||""),componentWillUnmount:function(){o(!1)},render:function(){return this.transferPropsTo(e(null,this.props.children))}});return t}var r=e("./ReactCompositeComponent"),o=e("./invariant");t.exports=n},{"./ReactCompositeComponent":33,"./invariant":118}],98:[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":21,"./createArrayFrom":96,"./getMarkupWrap":110,"./invariant":118}],99:[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":3}],100:[function(e,t){function n(e){return function(){return e}}function r(){}var o=e("./copyProperties");o(r,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(e){return e}}),t.exports=r},{"./copyProperties":95}],101:[function(e,t){"use strict";var n={};t.exports=n},{}],102:[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},{}],103:[function(e,t){"use strict";function n(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function r(e){if(null==e)return e;var t={};return o(e,n,t),t}{var o=e("./traverseAllChildren");e("./warning")}t.exports=r},{"./traverseAllChildren":138,"./warning":139}],104:[function(e,t){"use strict";function n(e){e.disabled||e.focus()}t.exports=n},{}],105:[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},{}],106:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],107:[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="charCode"in e?e.charCode:e.keyCode;return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":void r(!1)}var r=e("./invariant"),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},{"./invariant":118}],108:[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.toLowerCase()];return r&&n[r]}function r(){return n}var o={alt:"altKey",control:"ctrlKey",meta:"metaKey",shift:"shiftKey"};t.exports=r},{}],109:[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},{}],110:[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":21,"./invariant":118}],111:[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},{}],112:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],113:[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":21}],114:[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},{}],115:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],116:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e("./hyphenate"),o=/^ms-/;t.exports=n},{"./hyphenate":115}],117:[function(e,t){"use strict";function n(e){return e&&"function"==typeof e.type&&"function"==typeof e.type.prototype.mountComponent&&"function"==typeof e.type.prototype.receiveComponent}function r(e){return o(n(e)),new e.type(e)}var o=e("./invariant");t.exports=r},{"./invariant":118}],118:[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},{}],119:[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":21}],120:[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},{}],121:[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},{}],122:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":120}],123:[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+=" "+t);return e}t.exports=n},{}],124:[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":118}],125:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],126:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var r=0,o={};for(var i in e)e.hasOwnProperty(i)&&(o[i]=t.call(n,e[i],i,r++));return o}t.exports=n},{}],127:[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},{}],128:[function(e,t){"use strict";var n=e("./mergeInto"),r=function(e,t){var r={};return n(r,e),n(r,t),r};t.exports=r},{"./mergeInto":130}],129:[function(e,t){"use strict";var n=e("./invariant"),r=e("./keyMirror"),o=36,i=function(e){return"object"!=typeof e||null===e},a={MAX_MERGE_DEPTH:o,isTerminal:i,normalizeMergeArg:function(e){return void 0===e||null===e?{}:e},checkMergeArrayArgs:function(e,t){n(Array.isArray(e)&&Array.isArray(t))},checkMergeObjectArgs:function(e,t){a.checkMergeObjectArg(e),a.checkMergeObjectArg(t)},checkMergeObjectArg:function(e){n(!i(e)&&!Array.isArray(e))},checkMergeIntoObjectArg:function(e){n(!(i(e)&&"function"!=typeof e||Array.isArray(e)))},checkMergeLevel:function(e){n(o>e)},checkArrayStrategy:function(e){n(void 0===e||e in a.ArrayStrategies)},ArrayStrategies:r({Clobber:!0,IndexByIndex:!0})};t.exports=a},{"./invariant":118,"./keyMirror":124}],130:[function(e,t){"use strict";function n(e,t){if(i(e),null!=t){o(t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}}var r=e("./mergeHelpers"),o=r.checkMergeObjectArg,i=r.checkMergeIntoObjectArg;t.exports=n},{"./mergeHelpers":129}],131:[function(e,t){"use strict";var n=function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e.prototype[n]=t[n])};t.exports=n},{}],132:[function(e,t){"use strict";function n(e){r(e&&!/[^a-z0-9_]/.test(e))}var r=e("./invariant");t.exports=n},{"./invariant":118}],133:[function(e,t){"use strict";function n(e){return o(r.isValidDescriptor(e)),e}var r=e("./ReactDescriptor"),o=e("./invariant");t.exports=n},{"./ReactDescriptor":49,"./invariant":118}],134:[function(e,t){"use strict";var n=e("./ExecutionEnvironment"),r=function(e,t){e.innerHTML=t};if(n.canUseDOM){var o=document.createElement("div");o.innerHTML=" ",""===o.innerHTML&&(r=function(e,t){e.parentNode&&e.parentNode.replaceChild(e,e),t.match(/^[ \r\n\t\f]/)||"<"===t[0]&&(-1!==t.indexOf("<noscript")||-1!==t.indexOf("<script")||-1!==t.indexOf("<style")||-1!==t.indexOf("<meta")||-1!==t.indexOf("<link"))?(e.innerHTML=""+t,e.firstChild.deleteData(0,1)):e.innerHTML=t})}t.exports=r},{"./ExecutionEnvironment":21}],135:[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},{}],136:[function(e,t){"use strict";function n(e,t){return e&&t&&e.type===t.type&&(e.props&&e.props.key)===(t.props&&t.props.key)&&e._owner===t._owner?!0:!1}t.exports=n},{}],137:[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":118}],138:[function(e,t){"use strict";function n(e){return d[e]}function r(e,t){return e&&e.props&&null!=e.props.key?i(e.props.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("./ReactInstanceHandles"),u=e("./ReactTextComponent"),c=e("./invariant"),l=s.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,o,a){var s=0;if(Array.isArray(e))for(var d=0;d<e.length;d++){var f=e[d],v=t+(t?p:l)+r(f,d),m=n+s;s+=h(f,v,m,o,a)}else{var g=typeof e,y=""===t,C=y?l+r(e,0):t;if(null==e||"boolean"===g)o(a,null,C,n),s=1;else if(e.type&&e.type.prototype&&e.type.prototype.mountComponentIntoNode)o(a,e,C,n),s=1;else if("object"===g){c(!e||1!==e.nodeType);for(var E in e)e.hasOwnProperty(E)&&(s+=h(e[E],t+(t?p:l)+i(E)+p+r(e[E],0),n+s,o,a))}else if("string"===g){var R=u(e);o(a,R,C,n),s+=1}else if("number"===g){var M=u(""+e);o(a,M,C,n),s+=1}}return s};t.exports=a},{"./ReactInstanceHandles":57,"./ReactTextComponent":73,"./invariant":118}],139:[function(e,t){"use strict";var n=e("./emptyFunction"),r=n;t.exports=r},{"./emptyFunction":100}]},{},[27])(27)}); |
src/Fabric/Type/DateType.js | reactmob/dos-filter | import React from 'react';
import { DatePicker, DayOfWeek } from 'office-ui-fabric-react/lib/DatePicker';
import BaseDateType from '../../Type/DateType';
import AbstractRenderer from './AbstractRenderer';
const DayPickerStrings = {
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
shortMonths: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
],
days: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
],
shortDays: [
'S',
'M',
'T',
'W',
'T',
'F',
'S'
],
goToToday: 'Go to today',
prevMonthAriaLabel: 'Go to previous month',
nextMonthAriaLabel: 'Go to next month',
prevYearAriaLabel: 'Go to previous year',
nextYearAriaLabel: 'Go to next year'
};
export default class DateType extends BaseDateType {
static defaultProps = {
doRenderOperatorList: AbstractRenderer.doRenderOperatorList(),
};
/**
* @inheritDoc
*/
doRenderValueInput(value, onChange) {
return <DatePicker
value={value}
firstDayOfWeek={DayOfWeek.Monday}
strings={DayPickerStrings}
placeholder='Select a date...'
onSelectDate={(val) => onChange(val)}
/>
}
}
|
2018/cati/react/app/src/App.js | LorhanSohaky/UFSCar | import React, { Component } from 'react';
import PubSub from "pubsub-js";
import Axios from "axios";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import logo from './logo.svg';
import './App.css';
import HomePage from './HomePage';
import AddPage from './AddPage';
class App extends Component {
constructor(){
super();
this.state = {
'contacts': []
};
PubSub.subscribe("DELETE",this._handleDelete);
PubSub.subscribe("ADD",this._handleAdd);
}
componentDidMount(){
Axios.get("https://srv-contact.raccoon.ag/api/contacts").then(
(response) => {
this.setState({
contacts:response.data
});
}
);
}
_handleDelete = (msg, index) =>{
let id = this.state.contacts[index].id;
Axios.delete("https://srv-contact.raccoon.ag/api/contacts/"+id).then(
() => {
let list = this.state.contacts.slice();
list.splice(index,1);
this.setState({ contacts:list });
}
);
}
_handleAdd = (msg, contact) =>{
Axios.post("https://srv-contact.raccoon.ag/api/contacts", contact).then(
(response) => {
let list = this.state.contacts.slice();
list.push(response.data);
this.setState({ contacts:list });
}
);
}
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" render={()=> <HomePage contacts ={this.state.contacts} /> } />
<Route path="/add" component={AddPage} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
|
javascript/youtube-search/src/components/video_list_item.js | sandislonjsak/react-learning-projects | import React from 'react';
const VideoListItem = ({ video, onVideoSelect }) => {
const snippet = video.snippet;
const imageUrl = 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">{snippet.title}</div>
</div>
</div>
</li>
);
}
export default VideoListItem;
|
src/components/chart/charts/Bar.js | EKlevrai/courantderacines | import React, { Component } from 'react';
import './Bar.css';
import '../utils/toolTip/ToolTip.css';
import { BarChartData } from '../data/Data';
import { ToolTip } from '../utils/toolTip/ToolTip';
// TODO : cant import it correctly
const d3 = require('d3');
class Bar extends Component {
componentDidMount() {
const tooltip = ToolTip.create();
const w = 600;
const h = 500;
const padding = {top: 40, right: 40, bottom: 40, left:40};
const colorsPool = ['#1f77b4', '#2ca02c', '#ff7f0e', '#ff0d0d', '#ff0f87']
const colorsPoolHover = ['#81bdea', '#89de87', '#ffd2a8', '#ffa3a3', '#ffa8d2']
const colorHover = (i) => colorsPoolHover[i % colorsPoolHover.length];
const color = (i) => colorsPool[i % colorsPool.length];
//stacking the data into pile
// -adding a y0 value
// -the 'cat' field is transmitted to the skills
const data = BarChartData.map(cat => {
cat.skills = cat.skills.map((skill, index) => {
if (index === 0){
skill.y0 = 0;
} else {
skill.y0 = cat.skills[index - 1].y0 + cat.skills[index - 1].value;
}
skill.x = cat.cat;
return skill;
});
return cat;
})
//Scales : ordinal on x Axis, linear on y's
const xScale = d3.scale.ordinal()
.domain(['', 'front-end', 'back-end', 'data', 'infrastructure'])
.range([
0,
(w - padding.left - padding.right) * 0.1,
(w - padding.left - padding.right) * 0.35,
(w - padding.left - padding.right) * 0.60,
(w - padding.left - padding.right) * 0.85,
(w - padding.left - padding.right)
]);
const yScale = d3.scale.linear()
.domain([0,
d3.max( data, (e) => d3.max(e.skills, (e2) => e2.y0 + e2.value))
])
.range([h-padding.bottom-padding.top,0]);
const xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(0);
const yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(0);
//Create SVG element
const svg = d3.select("#bar")
.append("svg")
.attr("width", w)
.attr("height", h);
// Add a group for each col of data (skills categories)
const cats = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("class","rgroups")
.attr("transform","translate("+ padding.left + "," + (h - padding.bottom) +")");
// Add a rect for each data value
var rects = cats.selectAll("rect")
.data(d => d.skills)
.enter()
.append("rect")
// fill style
.style("fill-opacity",1)
.style("fill", (d, i) => color(d3.max(data, e => e.skills.indexOf(d))))
// sizes and positions of the rects
.attr("x", (d, i) => xScale(d.x))
.attr("y", (d) => -(- yScale(d.y0) - yScale(d.value) + (h - padding.top - padding.bottom)*2))
.attr("height", (d) => -yScale(d.value) + (h - padding.top - padding.bottom))
.attr("width", 30)
// mouseover event : tooltip and lighten the rect
.on("mouseover", (d) => {
ToolTip.on(tooltip, d.label);
rects.transition()
.duration(300)
.style("fill", (d2) =>
(d === d2) ? colorHover(d3.max(data, e => e.skills.indexOf(d)))
: color(d3.max(data, e => e.skills.indexOf(d2))));
})
// mouseout event : close tooltip and make all rect getting back their color
.on("mouseout", () => {
ToolTip.off(tooltip);
rects.transition()
.duration(300)
.style("fill", (d2) => color(d3.max(data, e => e.skills.indexOf(d2))));
});
// print axis
svg.append("g")
.attr("class","x axis")
.attr("transform","translate(40," + (h - padding.bottom) + ")")
.call(xAxis);
svg.append("g")
.attr("class","y axis")
.attr("transform","translate(" + padding.left + "," + padding.top + ")")
.call(yAxis);
}
render() {
return (
<div>
<h2>Skills</h2>
<div id={'bar'}/>
</div>
);
}
}
export default Bar;
|
src/containers/AddShoppingItem.js | kishigo/recipes-react-redux | /**
* Created by Kelvin Ishigo on 10/3/17.
*
* Copyright (c) 2017 Kelvin Ishigo
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
import React from 'react'
import {connect} from 'react-redux'
import {addShoppingItem} from '../actions'
let labelStyle = {
display: "inline-block",
float: "left",
clear: "left",
width: "5em"
};
let AddShoppingItem = ({dispatch}) => {
let shopping_item_name;
let shopping_item_qty;
let market_name;
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
if (!shopping_item_name.value.trim()) {
return
}
dispatch(addShoppingItem(shopping_item_name.value, shopping_item_qty.value, market_name.value));
shopping_item_name.value = '';
shopping_item_qty.value = '';
market_name.value = '';
}}
>
<label style={labelStyle}>item:</label><input
type="text"
name="item"
ref={node => {
shopping_item_name = node
}}
/>
<br/>
<label style={labelStyle}>qty: </label><input
type="text"
name="item"
ref={node => {
shopping_item_qty = node
}}
/>
<br/>
<label style={labelStyle}>market:</label> <input
type="text"
name="item"
ref={node => {
market_name = node
}}
/>
<br/>
<button type="submit">
Add Shopping Item
</button>
</form>
</div>
)
};
AddShoppingItem = connect()(AddShoppingItem);
export default AddShoppingItem |
ajax/libs/angular-google-maps/2.0.21/angular-google-maps.js | voronianski/cdnjs | /*! angular-google-maps 2.0.21 2015-06-04
* AngularJS directives for Google Maps
* git: https://github.com/angular-ui/angular-google-maps.git
*/
;
(function( window, angular, undefined ){
'use strict';
/*
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
angular-google-maps
https://github.com/angular-ui/angular-google-maps
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps.providers', []);
angular.module('uiGmapgoogle-maps.wrapped', []);
angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']);
angular.module('uiGmapgoogle-maps.directives.api.managers', []);
angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']);
angular.module('uiGmapgoogle-maps.directives.api.options.builders', []);
angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']);
angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']);
angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [
'$q', 'uiGmapuuid', function($q, uuid) {
var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId;
scriptId = void 0;
getScriptUrl = function(options) {
if (options.china) {
return 'http://maps.google.cn/maps/api/js?';
} else {
if (options.transport === 'auto') {
return '//maps.googleapis.com/maps/api/js?';
} else {
return options.transport + '://maps.googleapis.com/maps/api/js?';
}
}
};
includeScript = function(options) {
var omitOptions, query, script;
omitOptions = ['transport', 'isGoogleMapsForWork', 'china'];
if (options.isGoogleMapsForWork) {
omitOptions.push('key');
}
query = _.map(_.omit(options, omitOptions), function(v, k) {
return k + '=' + v;
});
if (scriptId) {
document.getElementById(scriptId).remove();
}
query = query.join('&');
script = document.createElement('script');
script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate());
script.type = 'text/javascript';
script.src = getScriptUrl(options) + query;
return document.body.appendChild(script);
};
isGoogleMapsLoaded = function() {
return angular.isDefined(window.google) && angular.isDefined(window.google.maps);
};
return {
load: function(options) {
var deferred, randomizedFunctionName;
deferred = $q.defer();
if (isGoogleMapsLoaded()) {
deferred.resolve(window.google.maps);
return deferred.promise;
}
randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000);
window[randomizedFunctionName] = function() {
window[randomizedFunctionName] = null;
deferred.resolve(window.google.maps);
};
if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) {
document.addEventListener('online', function() {
if (!isGoogleMapsLoaded()) {
return includeScript(options);
}
});
} else {
includeScript(options);
}
return deferred.promise;
}
};
}
]).provider('uiGmapGoogleMapApi', function() {
this.options = {
transport: 'https',
isGoogleMapsForWork: false,
china: false,
v: '3.17',
libraries: '',
language: 'en',
sensor: 'false'
};
this.configure = function(options) {
angular.extend(this.options, options);
};
this.$get = [
'uiGmapMapScriptLoader', (function(_this) {
return function(loader) {
return loader.load(_this.options);
};
})(this)
];
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() {
return {
init: _.once(function() {
if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) {
return;
}
google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open;
google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close;
google.maps.InfoWindow.prototype._isOpen = false;
google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) {
if (recurse != null) {
return;
}
this._isOpen = true;
this._open(map, anchor, true);
};
google.maps.InfoWindow.prototype.close = function(recurse) {
if (recurse != null) {
return;
}
this._isOpen = false;
this._close(true);
};
google.maps.InfoWindow.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
/*
Do the same for InfoBox
TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier
*/
if (window.InfoBox) {
window.InfoBox.prototype._open = window.InfoBox.prototype.open;
window.InfoBox.prototype._close = window.InfoBox.prototype.close;
window.InfoBox.prototype._isOpen = false;
window.InfoBox.prototype.open = function(map, anchor) {
this._isOpen = true;
this._open(map, anchor);
};
window.InfoBox.prototype.close = function() {
this._isOpen = false;
this._close();
};
window.InfoBox.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
}
if (window.MarkerLabel_) {
return window.MarkerLabel_.prototype.setContent = function() {
var content;
content = this.marker_.get('labelContent');
if (!content || _.isEqual(this.oldContent, content)) {
return;
}
if (typeof (content != null ? content.nodeType : void 0) === 'undefined') {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
this.oldContent = content;
} else {
this.labelDiv_.innerHTML = '';
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.labelDiv_.innerHTML = '';
this.eventDiv_.appendChild(content);
this.oldContent = content;
}
};
}
})
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() {
/*
Author Nick McCready
Intersection of Objects if the arrays have something in common each intersecting object will be returned
in an new array.
*/
this.intersectionObjects = function(array1, array2, comparison) {
var res;
if (comparison == null) {
comparison = void 0;
}
res = _.map(array1, (function(_this) {
return function(obj1) {
return _.find(array2, function(obj2) {
if (comparison != null) {
return comparison(obj1, obj2);
} else {
return _.isEqual(obj1, obj2);
}
});
};
})(this));
return _.filter(res, function(o) {
return o != null;
});
};
this.containsObject = _.includeObject = function(obj, target, comparison) {
if (comparison == null) {
comparison = void 0;
}
if (obj === null) {
return false;
}
return _.any(obj, (function(_this) {
return function(value) {
if (comparison != null) {
return comparison(value, target);
} else {
return _.isEqual(value, target);
}
};
})(this));
};
this.differenceObjects = function(array1, array2, comparison) {
if (comparison == null) {
comparison = void 0;
}
return _.filter(array1, (function(_this) {
return function(value) {
return !_this.containsObject(array2, value, comparison);
};
})(this));
};
this.withoutObjects = this.differenceObjects;
this.indexOfObject = function(array, item, comparison, isSorted) {
var i, length;
if (array == null) {
return -1;
}
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);
}
}
while (i < length) {
if (comparison != null) {
if (comparison(array[i], item)) {
return i;
}
} else {
if (_.isEqual(array[i], item)) {
return i;
}
}
i++;
}
return -1;
};
this.isNullOrUndefined = function(thing) {
return _.isNull(thing || _.isUndefined(thing));
};
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() {
return function(str) {
this.contains = function(value, fromIndex) {
return str.indexOf(value, fromIndex) !== -1;
};
return this;
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [
function() {
return {
fakePromise: function() {
var _cb;
_cb = void 0;
return {
then: function(cb) {
return _cb = cb;
},
resolve: function() {
return _cb.apply(void 0, arguments);
}
};
}
};
}
]).service('uiGmap_async', [
'$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) {
var ExposedPromise, PromiseQueueManager, SniffedPromise, _getArrayAndKeys, _getIterateeValue, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch;
promiseTypes = uiGmapPromise.promiseTypes;
isInProgress = uiGmapPromise.isInProgress;
promiseStatus = uiGmapPromise.promiseStatus;
ExposedPromise = uiGmapPromise.ExposedPromise;
SniffedPromise = uiGmapPromise.SniffedPromise;
kickPromise = function(sniffedPromise, cancelCb) {
var promise;
promise = sniffedPromise.promise();
promise.promiseType = sniffedPromise.promiseType;
if (promise.$$state) {
$log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status)));
}
promise.cancelCb = cancelCb;
return promise;
};
doSkippPromise = function(sniffedPromise, lastPromise) {
if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) {
$log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY");
return true;
}
return false;
};
maybeCancelPromises = function(queue, sniffedPromise, lastPromise) {
var first;
if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) {
if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) {
$log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType);
lastPromise.cancelCb('cancel safe');
first = queue.peek();
if ((first != null) && isInProgress(first)) {
if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) {
$log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType);
return first.cancelCb('cancel safe');
} else {
return $log.warn('first promise was not cancelable');
}
}
}
}
};
/*
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
*/
PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) {
var lastPromise, newPromise;
if (!existingPiecesObj.existingPieces) {
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue();
return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb));
} else {
lastPromise = _.last(existingPiecesObj.existingPieces._content);
if (doSkippPromise(sniffedPromise, lastPromise)) {
return;
}
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise);
newPromise = ExposedPromise(lastPromise["finally"](function() {
return kickPromise(sniffedPromise, cancelCb);
}));
newPromise.cancelCb = cancelCb;
newPromise.promiseType = sniffedPromise.promiseType;
existingPiecesObj.existingPieces.enqueue(newPromise);
return lastPromise["finally"](function() {
return existingPiecesObj.existingPieces.dequeue();
});
}
};
managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) {
var cancelLogger;
if (msg == null) {
msg = '';
}
cancelLogger = function(msg) {
$log.debug(msg + ": " + msg);
if ((cancelCb != null) && _.isFunction(cancelCb)) {
return cancelCb(msg);
}
};
return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger);
};
defaultChunkSize = 80;
errorObject = {
value: null
};
tryCatch = function(fn, ctx, args) {
var e;
try {
return fn.apply(ctx, args);
} catch (_error) {
e = _error;
errorObject.value = e;
return errorObject;
}
};
logTryCatch = function(fn, ctx, deferred, args) {
var msg, result;
result = tryCatch(fn, ctx, args);
if (result === errorObject) {
msg = "error within chunking iterator: " + errorObject.value;
$log.error(msg);
deferred.reject(msg);
}
if (result === 'cancel safe') {
return false;
}
return true;
};
_getIterateeValue = function(collection, array, index) {
var _isArray, valOrKey;
_isArray = collection === array;
valOrKey = array[index];
if (_isArray) {
return valOrKey;
}
return collection[valOrKey];
};
_getArrayAndKeys = function(collection, keys, bailOutCb, cb) {
var array;
if (angular.isArray(collection)) {
array = collection;
} else {
array = keys ? keys : Object.keys(_.omit(collection, ['length', 'forEach', 'map']));
keys = array;
}
if (cb == null) {
cb = bailOutCb;
}
if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) {
if (cb !== bailOutCb) {
return bailOutCb();
}
}
return cb(array, keys);
};
/*
Author: Nicholas McCready & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
*/
doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) {
return _getArrayAndKeys(collection, _keys, function(array, keys) {
var cnt, i, keepGoing, val;
if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) {
cnt = chunkSizeOrDontChunk;
} else {
cnt = array.length;
}
i = index;
keepGoing = true;
while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) {
val = _getIterateeValue(collection, array, i);
keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]);
++i;
}
if (array) {
if (keepGoing && i < array.length) {
index = i;
if (chunkSizeOrDontChunk) {
if ((pauseCb != null) && _.isFunction(pauseCb)) {
logTryCatch(pauseCb, void 0, overallD, []);
}
return $timeout(function() {
return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys);
}, pauseMilli, false);
}
} else {
return overallD.resolve();
}
}
});
};
each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var error, overallD, ret;
if (chunkSizeOrDontChunk == null) {
chunkSizeOrDontChunk = defaultChunkSize;
}
if (index == null) {
index = 0;
}
if (pauseMilli == null) {
pauseMilli = 1;
}
ret = void 0;
overallD = uiGmapPromise.defer();
ret = overallD.promise;
if (!pauseMilli) {
error = 'pause (delay) must be set from _async!';
$log.error(error);
overallD.reject(error);
return ret;
}
return _getArrayAndKeys(collection, _keys, function() {
overallD.resolve();
return ret;
}, function(array, keys) {
doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys);
return ret;
});
};
map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) {
var results;
results = [];
return _getArrayAndKeys(collection, _keys, function() {
return uiGmapPromise.resolve(results);
}, function(array, keys) {
return each(collection, function(o) {
return results.push(iterator(o));
}, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() {
return results;
});
});
};
return {
each: each,
map: map,
managePromiseQueue: managePromiseQueue,
promiseLock: managePromiseQueue,
defaultChunkSize: defaultChunkSize,
chunkSizeFrom: function(fromSize, ret) {
if (ret == null) {
ret = void 0;
}
if (_.isNumber(fromSize)) {
ret = fromSize;
}
if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) {
ret = false;
}
return ret;
}
};
}
]);
}).call(this);
;(function() {
var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() {
var BaseObject, baseObjectKeywords;
baseObjectKeywords = ['extended', 'included'];
BaseObject = (function() {
function BaseObject() {}
BaseObject.extend = function(obj) {
var key, ref, value;
for (key in obj) {
value = obj[key];
if (indexOf.call(baseObjectKeywords, key) < 0) {
this[key] = value;
}
}
if ((ref = obj.extended) != null) {
ref.apply(this);
}
return this;
};
BaseObject.include = function(obj) {
var key, ref, value;
for (key in obj) {
value = obj[key];
if (indexOf.call(baseObjectKeywords, key) < 0) {
this.prototype[key] = value;
}
}
if ((ref = obj.included) != null) {
ref.apply(this);
}
return this;
};
return BaseObject;
})();
return BaseObject;
});
}).call(this);
;
/*
Useful function callbacks that should be defined at later time.
Mainly to be used for specs to verify creation / linking.
This is to lead a common design in notifying child stuff.
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() {
return {
onChildCreation: function(child) {}
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [
'$q', function($q) {
var CtrlHandle;
return CtrlHandle = {
handle: function($scope, $element) {
$scope.$on('$destroy', function() {
return CtrlHandle.handle($scope);
});
$scope.deferred = $q.defer();
return {
getScope: function() {
return $scope;
}
};
},
mapPromise: function(scope, ctrl) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.deferred.promise.then(function(map) {
return scope.map = map;
});
return mapScope.deferred.promise;
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [
"uiGmapLogger", function($log) {
var _getEventsObj, _hasEvents;
_hasEvents = function(obj) {
return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events);
};
_getEventsObj = function(scope, model) {
if (_hasEvents(scope)) {
return scope;
}
if (_hasEvents(model)) {
return model;
}
};
return {
setEvents: function(gObject, scope, model, ignores) {
var eventObj;
eventObj = _getEventsObj(scope, model);
if (eventObj != null) {
return _.compact(_.map(eventObj.events, function(eventHandler, eventName) {
var doIgnore;
if (ignores) {
doIgnore = _(ignores).contains(eventName);
}
if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) {
return google.maps.event.addListener(gObject, eventName, function() {
if (!scope.$evalAsync) {
scope.$evalAsync = function() {};
}
return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments]));
});
}
}));
}
},
removeEvents: function(listeners) {
if (!listeners) {
return;
}
return listeners.forEach(function(l) {
if (l) {
return google.maps.event.removeListener(l);
}
});
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [
'uiGmapLogger', 'uiGmap_async', function($log, _async) {
return {
fit: function(gMarkers, gMap) {
var bounds, everSet;
if (gMap && gMarkers && gMarkers.length > 0) {
bounds = new google.maps.LatLngBounds();
everSet = false;
gMarkers.forEach((function(_this) {
return function(gMarker) {
if (gMarker) {
if (!everSet) {
everSet = true;
}
return bounds.extend(gMarker.getPosition());
}
};
})(this));
if (everSet) {
return gMap.fitBounds(bounds);
}
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [
'uiGmapLogger', '$compile', function(Logger, $compile) {
var _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords;
_isTruthy = function(value, bool, optionsArray) {
return value === bool || optionsArray.indexOf(value) !== -1;
};
_isFalse = function(value) {
return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']);
};
getLatitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[1];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[1];
} else {
return value.latitude;
}
};
getLongitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[0];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[0];
} else {
return value.longitude;
}
};
getCoords = function(value) {
if (!value) {
return;
}
if (Array.isArray(value) && value.length === 2) {
return new google.maps.LatLng(value[1], value[0]);
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]);
} else {
return new google.maps.LatLng(value.latitude, value.longitude);
}
};
validateCoords = function(coords) {
if (angular.isUndefined(coords)) {
return false;
}
if (_.isArray(coords)) {
if (coords.length === 2) {
return true;
}
} else if ((coords != null) && (coords != null ? coords.type : void 0)) {
if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) {
return true;
}
}
if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) {
return true;
}
return false;
};
return {
setCoordsFromEvent: function(prevValue, newLatLon) {
if (!prevValue) {
return;
}
if (Array.isArray(prevValue) && prevValue.length === 2) {
prevValue[1] = newLatLon.lat();
prevValue[0] = newLatLon.lng();
} else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') {
prevValue.coordinates[1] = newLatLon.lat();
prevValue.coordinates[0] = newLatLon.lng();
} else {
prevValue.latitude = newLatLon.lat();
prevValue.longitude = newLatLon.lng();
}
return prevValue;
},
getLabelPositionPoint: function(anchor) {
var xPos, yPos;
if (anchor === void 0) {
return void 0;
}
anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor);
xPos = parseFloat(anchor[1]);
yPos = parseFloat(anchor[2]);
if ((xPos != null) && (yPos != null)) {
return new google.maps.Point(xPos, yPos);
}
},
createWindowOptions: function(gMarker, scope, content, defaults) {
var options;
if ((content != null) && (defaults != null) && ($compile != null)) {
options = angular.extend({}, defaults, {
content: this.buildContent(scope, defaults, content),
position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords)
});
if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) {
if (options.boxClass == null) {
} else {
options.pixelOffset = {
height: 0,
width: -2
};
}
}
return options;
} else {
if (!defaults) {
Logger.error('infoWindow defaults not defined');
if (!content) {
return Logger.error('infoWindow content not defined');
}
} else {
return defaults;
}
}
},
buildContent: function(scope, defaults, content) {
var parsed, ret;
if (defaults.content != null) {
ret = defaults.content;
} else {
if ($compile != null) {
content = content.replace(/^\s+|\s+$/g, '');
parsed = content === '' ? '' : $compile(content)(scope);
if (parsed.length > 0) {
ret = parsed[0];
}
} else {
ret = content;
}
}
return ret;
},
defaultDelay: 50,
isTrue: function(value) {
return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']);
},
isFalse: _isFalse,
isFalsy: function(value) {
return _isTruthy(value, false, [void 0, null]) || _isFalse(value);
},
getCoords: getCoords,
validateCoords: validateCoords,
equalCoords: function(coord1, coord2) {
return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2);
},
validatePath: function(path) {
var array, i, polygon, trackMaxVertices;
i = 0;
if (angular.isUndefined(path.type)) {
if (!Array.isArray(path) || path.length < 2) {
return false;
}
while (i < path.length) {
if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) {
return false;
}
i++;
}
return true;
} else {
if (angular.isUndefined(path.coordinates)) {
return false;
}
if (path.type === 'Polygon') {
if (path.coordinates[0].length < 4) {
return false;
}
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
polygon = path.coordinates[trackMaxVertices.index];
array = polygon[0];
if (array.length < 4) {
return false;
}
} else if (path.type === 'LineString') {
if (path.coordinates.length < 2) {
return false;
}
array = path.coordinates;
} else {
return false;
}
while (i < array.length) {
if (array[i].length !== 2) {
return false;
}
i++;
}
return true;
}
},
convertPathPoints: function(path) {
var array, i, latlng, result, trackMaxVertices;
i = 0;
result = new google.maps.MVCArray();
if (angular.isUndefined(path.type)) {
while (i < path.length) {
latlng;
if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) {
latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude);
} else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') {
latlng = path[i];
}
result.push(latlng);
i++;
}
} else {
array;
if (path.type === 'Polygon') {
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
array = path.coordinates[trackMaxVertices.index][0];
} else if (path.type === 'LineString') {
array = path.coordinates;
}
while (i < array.length) {
result.push(new google.maps.LatLng(array[i][1], array[i][0]));
i++;
}
}
return result;
},
extendMapBounds: function(map, points) {
var bounds, i;
bounds = new google.maps.LatLngBounds();
i = 0;
while (i < points.length) {
bounds.extend(points.getAt(i));
i++;
}
return map.fitBounds(bounds);
},
getPath: function(object, key) {
var obj;
if ((key == null) || !_.isString(key)) {
return key;
}
obj = object;
_.each(key.split('.'), function(value) {
if (obj) {
return obj = obj[value];
}
});
return obj;
},
validateBoundPoints: function(bounds) {
if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) {
return false;
}
return true;
},
convertBoundPoints: function(bounds) {
var result;
result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude));
return result;
},
fitMapBounds: function(map, bounds) {
return map.fitBounds(bounds);
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [
'$q', '$timeout', function($q, $timeout) {
var _checkIfReady, _ctr, _currentCheckNum, _maxCtrChecks, _promises, _proms;
_ctr = 0;
_proms = [];
_currentCheckNum = 1;
_maxCtrChecks = 50;
_promises = function() {
return $q.all(_proms);
};
_checkIfReady = function(deferred, expectedInstances) {
return $timeout(function() {
if (_currentCheckNum >= _maxCtrChecks) {
deferred.reject('Your maps are not found we have checked the maximum amount of times. :)');
}
_currentCheckNum += 1;
if (_ctr !== expectedInstances) {
return _checkIfReady(deferred, expectedInstances);
} else {
return deferred.resolve(_promises());
}
}, 100);
};
return {
spawn: function() {
var d;
d = $q.defer();
_proms.push(d.promise);
_ctr += 1;
return {
instance: _ctr,
deferred: d
};
},
promises: _promises,
instances: function() {
return _ctr;
},
promise: function(expectedInstances) {
var d;
if (expectedInstances == null) {
expectedInstances = 1;
}
d = $q.defer();
_checkIfReady(d, expectedInstances);
return d.promise;
},
reset: function() {
_ctr = 0;
_proms.length = 0;
},
decrement: function() {
if (_ctr > 0) {
_ctr -= 1;
}
if (_proms.length) {
_proms.length -= 1;
}
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [
"uiGmapBaseObject", function(BaseObject) {
var Linked;
Linked = (function(superClass) {
extend(Linked, superClass);
function Linked(scope, element, attrs, ctrls) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.ctrls = ctrls;
}
return Linked;
})(BaseObject);
return Linked;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [
'$log', function($log) {
var LEVELS, Logger, log, maybeExecLevel;
LEVELS = {
log: 1,
info: 2,
debug: 3,
warn: 4,
error: 5,
none: 6
};
maybeExecLevel = function(level, current, fn) {
if (level >= current) {
return fn();
}
};
log = function(logLevelFnName, msg) {
if ($log != null) {
return $log[logLevelFnName](msg);
} else {
return console[logLevelFnName](msg);
}
};
Logger = (function() {
function Logger() {
var logFns;
this.doLog = true;
logFns = {};
['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) {
return function(level) {
return logFns[level] = function(msg) {
if (_this.doLog) {
return maybeExecLevel(LEVELS[level], _this.currentLevel, function() {
return log(level, msg);
});
}
};
};
})(this));
this.LEVELS = LEVELS;
this.currentLevel = LEVELS.error;
this.log = logFns['log'];
this.info = logFns['info'];
this.debug = logFns['debug'];
this.warn = logFns['warn'];
this.error = logFns['error'];
}
Logger.prototype.spawn = function() {
return new Logger();
};
Logger.prototype.setLog = function(someLogger) {
return $log = someLogger;
};
return Logger;
})();
return new Logger();
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) {
var ModelKey;
return ModelKey = (function(superClass) {
extend(ModelKey, superClass);
function ModelKey(scope1) {
this.scope = scope1;
this.modelsLength = bind(this.modelsLength, this);
this.updateChild = bind(this.updateChild, this);
this.destroy = bind(this.destroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.setChildScope = bind(this.setChildScope, this);
this.getChanges = bind(this.getChanges, this);
this.getProp = bind(this.getProp, this);
this.setIdKey = bind(this.setIdKey, this);
this.modelKeyComparison = bind(this.modelKeyComparison, this);
ModelKey.__super__.constructor.call(this);
this["interface"] = {};
this["interface"].scopeKeys = [];
this.defaultIdKey = 'id';
this.idKey = void 0;
}
ModelKey.prototype.evalModelHandle = function(model, modelKey) {
if ((model == null) || (modelKey == null)) {
return;
}
if (modelKey === 'self') {
return model;
} else {
if (_.isFunction(modelKey)) {
modelKey = modelKey();
}
return GmapUtil.getPath(model, modelKey);
}
};
ModelKey.prototype.modelKeyComparison = function(model1, model2) {
var hasCoords, isEqual, scope;
hasCoords = _.contains(this["interface"].scopeKeys, 'coords');
if (hasCoords && (this.scope.coords != null) || !hasCoords) {
scope = this.scope;
}
if (scope == null) {
throw 'No scope set!';
}
if (hasCoords) {
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
ModelKey.prototype.setIdKey = function(scope) {
return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey;
};
ModelKey.prototype.setVal = function(model, key, newValue) {
var thingToSet;
thingToSet = this.modelOrKey(model, key);
thingToSet = newValue;
return model;
};
ModelKey.prototype.modelOrKey = function(model, key) {
if (key == null) {
return;
}
if (key !== 'self') {
return GmapUtil.getPath(model, key);
}
return model;
};
ModelKey.prototype.getProp = function(propName, model) {
return this.modelOrKey(model, propName);
};
/*
For the cases were watching a large object we only want to know the list of props
that actually changed.
Also we want to limit the amount of props we analyze to whitelisted props that are
actually tracked by scope. (should make things faster with whitelisted)
*/
ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) {
var c, changes, prop;
if (whitelistedProps) {
prev = _.pick(prev, whitelistedProps);
now = _.pick(now, whitelistedProps);
}
changes = {};
prop = {};
c = {};
for (prop in now) {
if (!prev || prev[prop] !== now[prop]) {
if (_.isArray(now[prop])) {
changes[prop] = now[prop];
} else if (_.isObject(now[prop])) {
c = this.getChanges(now[prop], (prev ? prev[prop] : null));
if (!_.isEmpty(c)) {
changes[prop] = c;
}
} else {
changes[prop] = now[prop];
}
}
}
return changes;
};
ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) {
var maybeWrap, modelKey, modelProp, scopeProp;
if (doWrap == null) {
doWrap = false;
}
maybeWrap = function(isScope, ret, doWrap) {
if (doWrap == null) {
doWrap = false;
}
if (doWrap) {
return {
isScope: isScope,
value: ret
};
}
return ret;
};
scopeProp = scope[key];
if (_.isFunction(scopeProp)) {
return maybeWrap(true, scopeProp(model), doWrap);
}
if (_.isObject(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
if (!_.isString(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
modelKey = scopeProp;
if (!modelKey) {
modelProp = model[key];
} else {
modelProp = modelKey === 'self' ? model : model[modelKey];
}
if (_.isFunction(modelProp)) {
return maybeWrap(false, modelProp(), doWrap);
}
return maybeWrap(false, modelProp, doWrap);
};
ModelKey.prototype.setChildScope = function(keys, childScope, model) {
_.each(keys, (function(_this) {
return function(name) {
var isScopeObj, newValue;
isScopeObj = _this.scopeOrModelVal(name, childScope, model, true);
if ((isScopeObj != null ? isScopeObj.value : void 0) != null) {
newValue = isScopeObj.value;
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
}
};
})(this));
return childScope.model = model;
};
ModelKey.prototype.onDestroy = function(scope) {};
ModelKey.prototype.destroy = function(manualOverride) {
var ref;
if (manualOverride == null) {
manualOverride = false;
}
if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
} else {
return this.clean();
}
};
ModelKey.prototype.updateChild = function(child, model) {
if (model[this.idKey] == null) {
this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
return child.updateModel(model);
};
ModelKey.prototype.modelsLength = function(arrayOrObjModels) {
var len, toCheck;
if (arrayOrObjModels == null) {
arrayOrObjModels = void 0;
}
len = 0;
toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models;
if (toCheck == null) {
return len;
}
if (angular.isArray(toCheck) || (toCheck.length != null)) {
len = toCheck.length;
} else {
len = Object.keys(toCheck).length;
}
return len;
};
return ModelKey;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [
'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) {
return {
didQueueInitPromise: function(existingPiecesObj, scope) {
if (scope.models.length === 0) {
_async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) {
return function() {
return uiGmapPromise.resolve();
};
})(this)));
return true;
}
return false;
},
figureOutState: function(idKey, scope, childObjects, comparison, callBack) {
var adds, children, mappedScopeModelIds, removals, updates;
adds = [];
mappedScopeModelIds = {};
removals = [];
updates = [];
scope.models.forEach(function(m) {
var child;
if (m[idKey] != null) {
mappedScopeModelIds[m[idKey]] = {};
if (childObjects.get(m[idKey]) == null) {
return adds.push(m);
} else {
child = childObjects.get(m[idKey]);
if (!comparison(m, child.clonedModel)) {
return updates.push({
model: m,
child: child
});
}
}
} else {
return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion');
}
});
children = childObjects.values();
children.forEach(function(c) {
var id;
if (c == null) {
Logger.error('child undefined in ModelsWatcher.');
return;
}
if (c.model == null) {
Logger.error('child.model undefined in ModelsWatcher.');
return;
}
id = c.model[idKey];
if (mappedScopeModelIds[id] == null) {
return removals.push(c);
}
});
return {
adds: adds,
removals: removals,
updates: updates
};
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [
'$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) {
var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses;
promiseTypes = {
create: 'create',
update: 'update',
"delete": 'delete',
init: 'init'
};
promiseStatuses = {
IN_PROGRESS: 0,
RESOLVED: 1,
REJECTED: 2
};
strPromiseStatuses = (function() {
var obj;
obj = {};
obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress';
obj["" + promiseStatuses.RESOLVED] = 'resolved';
obj["" + promiseStatuses.REJECTED] = 'rejected';
return obj;
})();
isInProgress = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.IN_PROGRESS;
}
if (!promise.hasOwnProperty("$$v")) {
return true;
}
};
isResolved = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.RESOLVED;
}
if (promise.hasOwnProperty("$$v")) {
return true;
}
};
promiseStatus = function(status) {
return strPromiseStatuses[status] || 'done w error';
};
ExposedPromise = function(promise) {
var cancelDeferred, combined, wrapped;
cancelDeferred = $q.defer();
combined = $q.all([promise, cancelDeferred.promise]);
wrapped = $q.defer();
promise.then(cancelDeferred.resolve, (function() {}), function(notify) {
cancelDeferred.notify(notify);
return wrapped.notify(notify);
});
combined.then(function(successes) {
return wrapped.resolve(successes[0] || successes[1]);
}, function(error) {
return wrapped.reject(error);
});
wrapped.promise.cancel = function(reason) {
if (reason == null) {
reason = 'canceled';
}
return cancelDeferred.reject(reason);
};
wrapped.promise.notify = function(msg) {
if (msg == null) {
msg = 'cancel safe';
}
wrapped.notify(msg);
if (promise.hasOwnProperty('notify')) {
return promise.notify(msg);
}
};
if (promise.promiseType != null) {
wrapped.promise.promiseType = promise.promiseType;
}
return wrapped.promise;
};
SniffedPromise = function(fnPromise, promiseType) {
return {
promise: fnPromise,
promiseType: promiseType
};
};
defer = function() {
return $q.defer();
};
resolve = function() {
var d;
d = $q.defer();
d.resolve.apply(void 0, arguments);
return d.promise;
};
promise = function(fnToWrap) {
var d;
if (!_.isFunction(fnToWrap)) {
$log.error("uiGmapPromise.promise() only accepts functions");
return;
}
d = $q.defer();
$timeout(function() {
var result;
result = fnToWrap();
return d.resolve(result);
});
return d.promise;
};
return {
defer: defer,
promise: promise,
resolve: resolve,
promiseTypes: promiseTypes,
isInProgress: isInProgress,
isResolved: isResolved,
promiseStatus: promiseStatus,
ExposedPromise: ExposedPromise,
SniffedPromise: SniffedPromise
};
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() {
/*
Simple Object Map with a length property to make it easy to track length/size
*/
var PropMap;
return PropMap = (function() {
function PropMap() {
this.removeAll = bind(this.removeAll, this);
this.slice = bind(this.slice, this);
this.push = bind(this.push, this);
this.keys = bind(this.keys, this);
this.values = bind(this.values, this);
this.remove = bind(this.remove, this);
this.put = bind(this.put, this);
this.stateChanged = bind(this.stateChanged, this);
this.get = bind(this.get, this);
this.length = 0;
this.dict = {};
this.didValsStateChange = false;
this.didKeysStateChange = false;
this.allVals = [];
this.allKeys = [];
}
PropMap.prototype.get = function(key) {
return this.dict[key];
};
PropMap.prototype.stateChanged = function() {
this.didValsStateChange = true;
return this.didKeysStateChange = true;
};
PropMap.prototype.put = function(key, value) {
if (this.get(key) == null) {
this.length++;
}
this.stateChanged();
return this.dict[key] = value;
};
PropMap.prototype.remove = function(key, isSafe) {
var value;
if (isSafe == null) {
isSafe = false;
}
if (isSafe && !this.get(key)) {
return void 0;
}
value = this.dict[key];
delete this.dict[key];
this.length--;
this.stateChanged();
return value;
};
PropMap.prototype.valuesOrKeys = function(str) {
var keys, vals;
if (str == null) {
str = 'Keys';
}
if (!this["did" + str + "StateChange"]) {
return this['all' + str];
}
vals = [];
keys = [];
_.each(this.dict, function(v, k) {
vals.push(v);
return keys.push(k);
});
this.didKeysStateChange = false;
this.didValsStateChange = false;
this.allVals = vals;
this.allKeys = keys;
return this['all' + str];
};
PropMap.prototype.values = function() {
return this.valuesOrKeys('Vals');
};
PropMap.prototype.keys = function() {
return this.valuesOrKeys();
};
PropMap.prototype.push = function(obj, key) {
if (key == null) {
key = "key";
}
return this.put(obj[key], obj);
};
PropMap.prototype.slice = function() {
return this.keys().map((function(_this) {
return function(k) {
return _this.remove(k);
};
})(this));
};
PropMap.prototype.removeAll = function() {
return this.slice();
};
PropMap.prototype.each = function(cb) {
return _.each(this.dict, function(v, k) {
return cb(v);
});
};
PropMap.prototype.map = function(cb) {
return _.map(this.dict, function(v, k) {
return cb(v);
});
};
return PropMap;
})();
});
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [
"uiGmapLogger", function(Logger) {
var PropertyAction;
PropertyAction = function(setterFn) {
this.setIfChange = function(newVal, oldVal) {
var callingKey;
callingKey = this.exp;
if (!_.isEqual(oldVal, newVal)) {
return setterFn(callingKey, newVal);
}
};
this.sic = this.setIfChange;
return this;
};
return PropertyAction;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [
'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) {
var ClustererMarkerManager;
ClustererMarkerManager = (function() {
ClustererMarkerManager.type = 'ClustererMarkerManager';
function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) {
if (opt_markers == null) {
opt_markers = {};
}
this.opt_options = opt_options != null ? opt_options : {};
this.opt_events = opt_events;
this.checkSync = bind(this.checkSync, this);
this.getGMarkers = bind(this.getGMarkers, this);
this.fit = bind(this.fit, this);
this.destroy = bind(this.destroy, this);
this.clear = bind(this.clear, this);
this.draw = bind(this.draw, this);
this.removeMany = bind(this.removeMany, this);
this.remove = bind(this.remove, this);
this.addMany = bind(this.addMany, this);
this.update = bind(this.update, this);
this.add = bind(this.add, this);
this.type = ClustererMarkerManager.type;
this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options);
this.propMapGMarkers = new PropMap();
this.attachEvents(this.opt_events, 'opt_events');
this.clusterer.setIgnoreHidden(true);
this.noDrawOnSingleAddRemoves = true;
$log.info(this);
}
ClustererMarkerManager.prototype.checkKey = function(gMarker) {
var msg;
if (gMarker.key == null) {
msg = 'gMarker.key undefined and it is REQUIRED!!';
return $log.error(msg);
}
};
ClustererMarkerManager.prototype.add = function(gMarker) {
this.checkKey(gMarker);
this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.put(gMarker.key, gMarker);
return this.checkSync();
};
ClustererMarkerManager.prototype.update = function(gMarker) {
this.remove(gMarker);
return this.add(gMarker);
};
ClustererMarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.remove = function(gMarker) {
var exists;
this.checkKey(gMarker);
exists = this.propMapGMarkers.get(gMarker.key);
if (exists) {
this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.remove(gMarker.key);
}
return this.checkSync();
};
ClustererMarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.remove(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.draw = function() {
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.clear = function() {
this.removeMany(this.getGMarkers());
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) {
var eventHandler, eventName, results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info(optionsName + ": Attaching event: " + eventName + " to clusterer");
results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName]));
} else {
results.push(void 0);
}
}
return results;
}
};
ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) {
var eventHandler, eventName, results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info(optionsName + ": Clearing event: " + eventName + " to clusterer");
results.push(google.maps.event.clearListeners(this.clusterer, eventName));
} else {
results.push(void 0);
}
}
return results;
}
};
ClustererMarkerManager.prototype.destroy = function() {
this.clearEvents(this.opt_events, 'opt_events');
return this.clear();
};
ClustererMarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap());
};
ClustererMarkerManager.prototype.getGMarkers = function() {
return this.clusterer.getMarkers().values();
};
ClustererMarkerManager.prototype.checkSync = function() {};
return ClustererMarkerManager;
})();
return ClustererMarkerManager;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [
"uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) {
var MarkerManager;
MarkerManager = (function() {
MarkerManager.type = 'MarkerManager';
function MarkerManager(gMap, opt_markers, opt_options) {
this.getGMarkers = bind(this.getGMarkers, this);
this.fit = bind(this.fit, this);
this.handleOptDraw = bind(this.handleOptDraw, this);
this.clear = bind(this.clear, this);
this.draw = bind(this.draw, this);
this.removeMany = bind(this.removeMany, this);
this.remove = bind(this.remove, this);
this.addMany = bind(this.addMany, this);
this.update = bind(this.update, this);
this.add = bind(this.add, this);
this.type = MarkerManager.type;
this.gMap = gMap;
this.gMarkers = new PropMap();
this.$log = Logger;
this.$log.info(this);
}
MarkerManager.prototype.add = function(gMarker, optDraw) {
var exists, msg;
if (optDraw == null) {
optDraw = true;
}
if (gMarker.key == null) {
msg = "gMarker.key undefined and it is REQUIRED!!";
Logger.error(msg);
throw msg;
}
exists = this.gMarkers.get(gMarker.key);
if (!exists) {
this.handleOptDraw(gMarker, optDraw, true);
return this.gMarkers.put(gMarker.key, gMarker);
}
};
MarkerManager.prototype.update = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.remove(gMarker, optDraw);
return this.add(gMarker, optDraw);
};
MarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
MarkerManager.prototype.remove = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.handleOptDraw(gMarker, optDraw, false);
if (this.gMarkers.get(gMarker.key)) {
return this.gMarkers.remove(gMarker.key);
}
};
MarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(marker) {
return _this.remove(marker);
};
})(this));
};
MarkerManager.prototype.draw = function() {
var deletes;
deletes = [];
this.gMarkers.each((function(_this) {
return function(gMarker) {
if (!gMarker.isDrawn) {
if (gMarker.doAdd) {
gMarker.setMap(_this.gMap);
return gMarker.isDrawn = true;
} else {
return deletes.push(gMarker);
}
}
};
})(this));
return deletes.forEach((function(_this) {
return function(gMarker) {
gMarker.isDrawn = false;
return _this.remove(gMarker, true);
};
})(this));
};
MarkerManager.prototype.clear = function() {
this.gMarkers.each(function(gMarker) {
return gMarker.setMap(null);
});
delete this.gMarkers;
return this.gMarkers = new PropMap();
};
MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) {
if (optDraw === true) {
if (doAdd) {
gMarker.setMap(this.gMap);
} else {
gMarker.setMap(null);
}
return gMarker.isDrawn = true;
} else {
gMarker.isDrawn = false;
return gMarker.doAdd = doAdd;
}
};
MarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.gMap);
};
MarkerManager.prototype.getGMarkers = function() {
return this.gMarkers.values();
};
return MarkerManager;
})();
return MarkerManager;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [
'$timeout', function($timeout) {
var addEvent, addEvents;
addEvent = function(target, eventName, handler) {
return google.maps.event.addListener(target, eventName, function() {
handler.apply(this, arguments);
return $timeout((function() {}), true);
});
};
addEvents = function(target, eventName, handler) {
var remove;
if (handler) {
return addEvent(target, eventName, handler);
}
remove = [];
angular.forEach(eventName, function(_handler, key) {
return remove.push(addEvent(target, key, _handler));
});
return function() {
angular.forEach(remove, function(listener) {
return google.maps.event.removeListener(listener);
});
return remove = null;
};
};
return addEvents;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [
'uiGmapadd-events', function(mapEvents) {
return function(mapArray, scope, pathEval, pathChangedFn) {
var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener;
isSetFromScope = false;
scopePath = scope.$eval(pathEval);
if (!scope["static"]) {
legacyHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath[index] = value;
} else {
scopePath[index].latitude = value.lat();
return scopePath[index].longitude = value.lng();
}
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath.splice(index, 0, value);
} else {
return scopePath.splice(index, 0, {
latitude: value.lat(),
longitude: value.lng()
});
}
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return scopePath.splice(index, 1);
}
};
geojsonArray;
if (scopePath.type === 'Polygon') {
geojsonArray = scopePath.coordinates[0];
} else if (scopePath.type === 'LineString') {
geojsonArray = scopePath.coordinates;
}
geojsonHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
geojsonArray[index][1] = value.lat();
return geojsonArray[index][0] = value.lng();
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
return geojsonArray.splice(index, 0, [value.lng(), value.lat()]);
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return geojsonArray.splice(index, 1);
}
};
mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers);
}
legacyWatcher = function(newPath) {
var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
i = 0;
oldLength = oldArray.getLength();
newLength = newPath.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = newPath[i];
if (typeof newValue.equals === 'function') {
if (!newValue.equals(oldValue)) {
oldArray.setAt(i, newValue);
changed = true;
}
} else {
if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) {
oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude));
changed = true;
}
}
i++;
}
while (i < newLength) {
newValue = newPath[i];
if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') {
oldArray.push(newValue);
} else {
oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude));
}
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
geojsonWatcher = function(newPath) {
var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
array;
if (scopePath.type === 'Polygon') {
array = newPath.coordinates[0];
} else if (scopePath.type === 'LineString') {
array = newPath.coordinates;
}
i = 0;
oldLength = oldArray.getLength();
newLength = array.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = array[i];
if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) {
oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
}
i++;
}
while (i < newLength) {
newValue = array[i];
oldArray.push(new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
watchListener;
if (!scope["static"]) {
if (angular.isUndefined(scopePath.type)) {
watchListener = scope.$watchCollection(pathEval, legacyWatcher);
} else {
watchListener = scope.$watch(pathEval, geojsonWatcher, true);
}
}
return function() {
if (mapArrayListener) {
mapArrayListener();
mapArrayListener = null;
}
if (watchListener) {
watchListener();
return watchListener = null;
}
};
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [
'$timeout', function($timeout) {
return {
maybeRepaint: function(el) {
if (el) {
el.style.opacity = 0.9;
return $timeout(function() {
return el.style.opacity = 1;
});
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() {
var _ignores, _iterators, _slapForEach, _slapMap;
_ignores = ['length', 'forEach', 'map'];
_iterators = [];
_slapForEach = function(object) {
object.forEach = function(cb) {
return _.each(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapForEach);
_slapMap = function(object) {
object.map = function(cb) {
return _.map(_.omit(object, _ignores), function(val) {
if (!_.isFunction(val)) {
return cb(val);
}
});
};
return object;
};
_iterators.push(_slapMap);
return {
slapMap: _slapMap,
slapForEach: _slapForEach,
slapAll: function(object) {
_iterators.forEach(function(it) {
return it(object);
});
return object;
}
};
});
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) {
var CommonOptionsBuilder;
return CommonOptionsBuilder = (function(superClass) {
extend(CommonOptionsBuilder, superClass);
function CommonOptionsBuilder() {
this.watchProps = bind(this.watchProps, this);
this.buildOpts = bind(this.buildOpts, this);
return CommonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CommonOptionsBuilder.prototype.props = [
'clickable', 'draggable', 'editable', 'visible', {
prop: 'stroke',
isColl: true
}
];
CommonOptionsBuilder.prototype.getCorrectModel = function(scope) {
if (angular.isDefined(scope != null ? scope.model : void 0)) {
return scope.model;
} else {
return scope;
}
};
CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var model, opts, stroke;
if (customOpts == null) {
customOpts = {};
}
if (forEachOpts == null) {
forEachOpts = {};
}
if (!this.scope) {
$log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts');
return;
}
if (!this.map) {
$log.error('this.map not defined in CommonOptionsBuilder can not buildOpts');
return;
}
model = this.getCorrectModel(this.scope);
stroke = this.scopeOrModelVal('stroke', this.scope, model);
opts = angular.extend(customOpts, this.DEFAULTS, {
map: this.map,
strokeColor: stroke != null ? stroke.color : void 0,
strokeOpacity: stroke != null ? stroke.opacity : void 0,
strokeWeight: stroke != null ? stroke.weight : void 0
});
angular.forEach(angular.extend(forEachOpts, {
clickable: true,
draggable: false,
editable: false,
"static": false,
fit: false,
visible: true,
zIndex: 0,
icons: []
}), (function(_this) {
return function(defaultValue, key) {
var val;
val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model);
if (angular.isUndefined(val)) {
return opts[key] = defaultValue;
} else {
return opts[key] = model[key];
}
};
})(this));
if (opts["static"]) {
opts.editable = false;
}
return opts;
};
CommonOptionsBuilder.prototype.watchProps = function(props) {
if (props == null) {
props = this.props;
}
return props.forEach((function(_this) {
return function(prop) {
if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) {
if (prop != null ? prop.isColl : void 0) {
return _this.scope.$watchCollection(prop.prop, _this.setMyOptions);
} else {
return _this.scope.$watch(prop, _this.setMyOptions);
}
}
};
})(this));
};
return CommonOptionsBuilder;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var PolylineOptionsBuilder;
return PolylineOptionsBuilder = (function(superClass) {
extend(PolylineOptionsBuilder, superClass);
function PolylineOptionsBuilder() {
return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolylineOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolylineOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapShapeOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var ShapeOptionsBuilder;
return ShapeOptionsBuilder = (function(superClass) {
extend(ShapeOptionsBuilder, superClass);
function ShapeOptionsBuilder() {
return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments);
}
ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) {
var fill, model;
model = this.getCorrectModel(this.scope);
fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model);
customOpts = angular.extend(customOpts, {
fillColor: fill != null ? fill.color : void 0,
fillOpacity: fill != null ? fill.opacity : void 0
});
return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts);
};
return ShapeOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapPolygonOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var PolygonOptionsBuilder;
return PolygonOptionsBuilder = (function(superClass) {
extend(PolygonOptionsBuilder, superClass);
function PolygonOptionsBuilder() {
return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) {
return PolygonOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, cachedEval, {
geodesic: false
});
};
return PolygonOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapRectangleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var RectangleOptionsBuilder;
return RectangleOptionsBuilder = (function(superClass) {
extend(RectangleOptionsBuilder, superClass);
function RectangleOptionsBuilder() {
return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) {
return RectangleOptionsBuilder.__super__.buildOpts.call(this, {
bounds: bounds
}, cachedEval);
};
return RectangleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapCircleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var CircleOptionsBuilder;
return CircleOptionsBuilder = (function(superClass) {
extend(CircleOptionsBuilder, superClass);
function CircleOptionsBuilder() {
return CircleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) {
return CircleOptionsBuilder.__super__.buildOpts.call(this, {
center: center,
radius: radius
}, cachedEval);
};
return CircleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [
'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) {
return _.extend(GmapUtil, {
createOptions: function(coords, icon, defaults, map) {
var opts;
if (defaults == null) {
defaults = {};
}
opts = angular.extend({}, defaults, {
position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords),
visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords)
});
if ((defaults.icon != null) || (icon != null)) {
opts = angular.extend(opts, {
icon: defaults.icon != null ? defaults.icon : icon
});
}
if (map != null) {
opts.map = map;
}
return opts;
},
isLabel: function(options) {
if (options == null) {
return false;
}
return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null);
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [
'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) {
return function(Builder, gFactory) {
var BasePolyChildModel;
return BasePolyChildModel = (function(superClass) {
extend(BasePolyChildModel, superClass);
BasePolyChildModel.include(GmapUtil);
function BasePolyChildModel(scope, attrs, map, defaults, model) {
var create;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.defaults = defaults;
this.model = model;
this.clean = bind(this.clean, this);
this.clonedModel = _.clone(this.model, true);
this.isDragging = false;
this.internalEvents = {
dragend: (function(_this) {
return function() {
return _.defer(function() {
return _this.isDragging = false;
});
};
})(this),
dragstart: (function(_this) {
return function() {
return _this.isDragging = true;
};
})(this)
};
create = (function(_this) {
return function() {
var maybeCachedEval, pathPoints;
if (_this.isDragging) {
return;
}
pathPoints = _this.convertPathPoints(_this.scope.path);
if (_this.gObject != null) {
_this.clean();
}
if (_this.scope.model != null) {
maybeCachedEval = _this.scope;
}
if (pathPoints.length > 0) {
_this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval));
}
if (_this.gObject) {
if (_this.scope.fit) {
_this.extendMapBounds(_this.map, pathPoints);
}
arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) {
if (_this.scope.fit) {
return _this.extendMapBounds(_this.map, pathPoints);
}
});
if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) {
_this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope);
}
return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.model) : EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.scope);
}
};
})(this);
create();
this.scope.$watch('path', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.gObject) {
return create();
}
};
})(this), true);
if (!this.scope["static"] && angular.isDefined(this.scope.editable)) {
this.scope.$watch('editable', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setEditable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.draggable)) {
this.scope.$watch('draggable', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setDraggable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.visible)) {
this.scope.$watch('visible', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
}
return (ref = _this.gObject) != null ? ref.setVisible(newValue) : void 0;
};
})(this), true);
}
if (angular.isDefined(this.scope.geodesic)) {
this.scope.$watch('geodesic', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) {
this.scope.$watch('stroke.weight', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) {
this.scope.$watch('stroke.color', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) {
this.scope.$watch('stroke.opacity', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(this.scope.icons)) {
this.scope.$watch('icons', (function(_this) {
return function(newValue, oldValue) {
var ref;
if (newValue !== oldValue) {
return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.clean();
return _this.scope = null;
};
})(this));
if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) {
this.scope.$watch('fill.color', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) {
this.scope.$watch('fill.opacity', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(this.scope.zIndex)) {
this.scope.$watch('zIndex', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
}
BasePolyChildModel.prototype.clean = function() {
var ref;
EventsHelper.removeEvents(this.listeners);
EventsHelper.removeEvents(this.internalListeners);
if ((ref = this.gObject) != null) {
ref.setMap(null);
}
return this.gObject = null;
};
return BasePolyChildModel;
})(Builder);
};
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , &
http://jsfiddle.net/YsQdh/88/
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [
'uiGmapLogger', '$q', function($log, $q) {
var drawFreeHand, freeHandMgr;
drawFreeHand = function(map, polys, enable) {
var move, poly;
poly = new google.maps.Polyline({
map: map,
clickable: false
});
move = google.maps.event.addListener(map, 'mousemove', function(e) {
return poly.getPath().push(e.latLng);
});
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
var path;
google.maps.event.removeListener(move);
path = poly.getPath();
poly.setMap(null);
polys.push(new google.maps.Polygon({
map: map,
path: path
}));
poly = null;
google.maps.event.clearListeners(map.getDiv(), 'mousedown');
return enable();
});
return void 0;
};
freeHandMgr = function(map1, defaultOptions) {
var disableMap, enable;
this.map = map1;
if (!defaultOptions) {
defaultOptions = {
draggable: true,
zoomControl: true,
scrollwheel: true,
disableDoubleClickZoom: true
};
}
enable = (function(_this) {
return function() {
var ref;
if ((ref = _this.deferred) != null) {
ref.resolve();
}
return _.defer(function() {
return _this.map.setOptions(_.extend(_this.oldOptions, defaultOptions));
});
};
})(this);
disableMap = (function(_this) {
return function() {
$log.info('disabling map move');
_this.oldOptions = map.getOptions();
_this.oldOptions.center = map.getCenter();
return _this.map.setOptions({
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false
});
};
})(this);
this.engage = (function(_this) {
return function(polys1) {
_this.polys = polys1;
_this.deferred = $q.defer();
disableMap();
$log.info('DrawFreeHandChildModel is engaged (drawing).');
google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) {
return drawFreeHand(_this.map, _this.polys, enable);
});
return _this.deferred.promise;
};
})(this);
return this;
};
return freeHandMgr;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) {
var MarkerChildModel;
MarkerChildModel = (function(superClass) {
var destroy;
extend(MarkerChildModel, superClass);
MarkerChildModel.include(GmapUtil);
MarkerChildModel.include(EventsHelper);
MarkerChildModel.include(MarkerOptions);
destroy = function(child) {
if ((child != null ? child.gObject : void 0) != null) {
child.removeEvents(child.externalListeners);
child.removeEvents(child.internalListeners);
if (child != null ? child.gObject : void 0) {
if (child.removeFromManager) {
child.gManager.remove(child.gObject);
}
child.gObject.setMap(null);
return child.gObject = null;
}
}
};
function MarkerChildModel(scope, model1, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) {
var action;
this.model = model1;
this.keys = keys;
this.gMap = gMap;
this.defaults = defaults;
this.doClick = doClick;
this.gManager = gManager;
this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true;
this.trackModel = trackModel != null ? trackModel : true;
this.needRedraw = needRedraw != null ? needRedraw : false;
this.internalEvents = bind(this.internalEvents, this);
this.setLabelOptions = bind(this.setLabelOptions, this);
this.setOptions = bind(this.setOptions, this);
this.setIcon = bind(this.setIcon, this);
this.setCoords = bind(this.setCoords, this);
this.isNotValid = bind(this.isNotValid, this);
this.maybeSetScopeValue = bind(this.maybeSetScopeValue, this);
this.createMarker = bind(this.createMarker, this);
this.setMyScope = bind(this.setMyScope, this);
this.updateModel = bind(this.updateModel, this);
this.handleModelChanges = bind(this.handleModelChanges, this);
this.destroy = bind(this.destroy, this);
this.clonedModel = _.extend({}, this.model);
this.deferred = uiGmapPromise.defer();
_.each(this.keys, (function(_this) {
return function(v, k) {
return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k];
};
})(this));
this.idKey = this.idKeyKey || 'id';
if (this.model[this.idKey] != null) {
this.id = this.model[this.idKey];
}
MarkerChildModel.__super__.constructor.call(this, scope);
this.scope.getGMarker = (function(_this) {
return function() {
return _this.gObject;
};
})(this);
this.firstTime = true;
if (this.trackModel) {
this.scope.model = this.model;
this.scope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.handleModelChanges(newValue, oldValue);
}
};
})(this), true);
} else {
action = new PropertyAction((function(_this) {
return function(calledKey, newVal) {
if (!_this.firstTime) {
return _this.setMyScope(calledKey, scope);
}
};
})(this), false);
_.each(this.keys, function(v, k) {
return scope.$watch(k, action.sic, true);
});
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return destroy(_this);
};
})(this));
this.createMarker(this.model);
$log.info(this);
}
MarkerChildModel.prototype.destroy = function(removeFromManager) {
if (removeFromManager == null) {
removeFromManager = true;
}
this.removeFromManager = removeFromManager;
return this.scope.$destroy();
};
MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) {
var changes, ctr, len;
changes = this.getChanges(newValue, oldValue, IMarker.keys);
if (!this.firstTime) {
ctr = 0;
len = _.keys(changes).length;
return _.each(changes, (function(_this) {
return function(v, k) {
var doDraw;
ctr += 1;
doDraw = len === ctr;
_this.setMyScope(k, newValue, oldValue, false, true, doDraw);
return _this.needRedraw = true;
};
})(this));
}
};
MarkerChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return this.setMyScope('all', model, this.model);
};
MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) {
var coords;
if (doDraw == null) {
doDraw = true;
}
coords = this.getProp(this.coordsKey, this.model);
if (coords != null) {
if (!this.validateCoords(coords)) {
$log.debug('MarkerChild does not have coords yet. They may be defined later.');
return;
}
if (validCb != null) {
validCb();
}
if (doDraw && this.gObject) {
return this.gManager.add(this.gObject);
}
} else {
if (doDraw && this.gObject) {
return this.gManager.remove(this.gObject);
}
}
};
MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) {
var justCreated;
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
if (model == null) {
model = this.model;
} else {
this.model = model;
}
if (!this.gObject) {
this.setOptions(this.scope, doDraw);
justCreated = true;
}
switch (thingThatChanged) {
case 'all':
return _.each(this.keys, (function(_this) {
return function(v, k) {
return _this.setMyScope(k, model, oldModel, isInit, doDraw);
};
})(this));
case 'icon':
return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw);
case 'coords':
return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw);
case 'options':
if (!justCreated) {
return this.createMarker(model, oldModel, isInit, doDraw);
}
}
};
MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) {
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw);
return this.firstTime = false;
};
MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) {
if (gSetter == null) {
gSetter = void 0;
}
if (doDraw == null) {
doDraw = true;
}
if (gSetter != null) {
return gSetter(this.scope, doDraw);
}
};
if (MarkerChildModel.doDrawSelf && doDraw) {
MarkerChildModel.gManager.draw();
}
MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) {
var hasIdenticalScopes, hasNoGmarker;
if (doCheckGmarker == null) {
doCheckGmarker = true;
}
hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0;
hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false;
return hasIdenticalScopes || hasNoGmarker;
};
MarkerChildModel.prototype.setCoords = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var newGValue, newModelVal, oldGValue;
newModelVal = _this.getProp(_this.coordsKey, _this.model);
newGValue = _this.getCoords(newModelVal);
oldGValue = _this.gObject.getPosition();
if ((oldGValue != null) && (newGValue != null)) {
if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) {
return;
}
}
_this.gObject.setPosition(newGValue);
return _this.gObject.setVisible(_this.validateCoords(newModelVal));
};
})(this));
};
MarkerChildModel.prototype.setIcon = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, newValue, oldValue;
oldValue = _this.gObject.getIcon();
newValue = _this.getProp(_this.iconKey, _this.model);
if (oldValue === newValue) {
return;
}
_this.gObject.setIcon(newValue);
coords = _this.getProp(_this.coordsKey, _this.model);
_this.gObject.setPosition(_this.getCoords(coords));
return _this.gObject.setVisible(_this.validateCoords(coords));
};
})(this));
};
MarkerChildModel.prototype.setOptions = function(scope, doDraw) {
var ref;
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope, false)) {
return;
}
this.renderGMarker(doDraw, (function(_this) {
return function() {
var _options, coords, icon;
coords = _this.getProp(_this.coordsKey, _this.model);
icon = _this.getProp(_this.iconKey, _this.model);
_options = _this.getProp(_this.optionsKey, _this.model);
_this.opts = _this.createOptions(coords, icon, _options);
if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) {
_this.gManager.remove(_this.gObject);
_this.gObject = void 0;
}
if (_this.gObject != null) {
_this.gObject.setOptions(_this.setLabelOptions(_this.opts));
}
if (!_this.gObject) {
if (_this.isLabel(_this.opts)) {
_this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts));
} else {
_this.gObject = new google.maps.Marker(_this.opts);
}
_.extend(_this.gObject, {
model: _this.model
});
}
if (_this.externalListeners) {
_this.removeEvents(_this.externalListeners);
}
if (_this.internalListeners) {
_this.removeEvents(_this.internalListeners);
}
_this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']);
_this.internalListeners = _this.setEvents(_this.gObject, {
events: _this.internalEvents(),
$evalAsync: function() {}
}, _this.model);
if (_this.id != null) {
return _this.gObject.key = _this.id;
}
};
})(this));
if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) {
this.deferred.resolve(this.gObject);
} else {
if (!this.gObject) {
return this.deferred.reject('gObject is null');
}
if (!(((ref = this.gObject) != null ? ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) {
$log.debug('gObject has no map yet');
this.deferred.resolve(this.gObject);
}
}
if (this.model[this.fitKey]) {
return this.gManager.fit();
}
};
MarkerChildModel.prototype.setLabelOptions = function(opts) {
opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor);
return opts;
};
MarkerChildModel.prototype.internalEvents = function() {
return {
dragend: (function(_this) {
return function(marker, eventName, model, mousearg) {
var events, modelToSet, newCoords;
modelToSet = _this.trackModel ? _this.scope.model : _this.model;
newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition());
modelToSet = _this.setVal(model, _this.coordsKey, newCoords);
events = _this.scope.events;
if ((events != null ? events.dragend : void 0) != null) {
events.dragend(marker, eventName, modelToSet, mousearg);
}
return _this.scope.$apply();
};
})(this),
click: (function(_this) {
return function(marker, eventName, model, mousearg) {
var click;
click = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _this.model);
if (_this.doClick && (click != null)) {
return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg));
}
};
})(this)
};
};
return MarkerChildModel;
})(ModelKey);
return MarkerChildModel;
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) {
var PolygonChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polygon(opts);
};
base = new BaseGen(Builder, gFactory);
return PolygonChildModel = (function(superClass) {
extend(PolygonChildModel, superClass);
function PolygonChildModel() {
return PolygonChildModel.__super__.constructor.apply(this, arguments);
}
return PolygonChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) {
var PolylineChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polyline(opts);
};
base = BaseGen(Builder, gFactory);
return PolylineChildModel = (function(superClass) {
extend(PolylineChildModel, superClass);
function PolylineChildModel() {
return PolylineChildModel.__super__.constructor.apply(this, arguments);
}
return PolylineChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) {
var WindowChildModel;
WindowChildModel = (function(superClass) {
extend(WindowChildModel, superClass);
WindowChildModel.include(GmapUtil);
WindowChildModel.include(EventsHelper);
function WindowChildModel(model1, scope1, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) {
var maybeMarker;
this.model = model1;
this.scope = scope1;
this.opts = opts;
this.isIconVisibleOnClick = isIconVisibleOnClick;
this.mapCtrl = mapCtrl;
this.markerScope = markerScope;
this.element = element;
this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false;
this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true;
this.updateModel = bind(this.updateModel, this);
this.destroy = bind(this.destroy, this);
this.remove = bind(this.remove, this);
this.getLatestPosition = bind(this.getLatestPosition, this);
this.hideWindow = bind(this.hideWindow, this);
this.showWindow = bind(this.showWindow, this);
this.handleClick = bind(this.handleClick, this);
this.watchOptions = bind(this.watchOptions, this);
this.watchCoords = bind(this.watchCoords, this);
this.createGWin = bind(this.createGWin, this);
this.watchElement = bind(this.watchElement, this);
this.watchAndDoShow = bind(this.watchAndDoShow, this);
this.doShow = bind(this.doShow, this);
this.clonedModel = _.clone(this.model, true);
this.getGmarker = function() {
var ref, ref1;
if (((ref = this.markerScope) != null ? ref['getGMarker'] : void 0) != null) {
return (ref1 = this.markerScope) != null ? ref1.getGMarker() : void 0;
}
};
this.listeners = [];
this.createGWin();
maybeMarker = this.getGmarker();
if (maybeMarker != null) {
maybeMarker.setClickable(true);
}
this.watchElement();
this.watchOptions();
this.watchCoords();
this.watchAndDoShow();
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.destroy();
};
})(this));
$log.info(this);
}
WindowChildModel.prototype.doShow = function(wasOpen) {
if (this.scope.show === true || wasOpen) {
return this.showWindow();
} else {
return this.hideWindow();
}
};
WindowChildModel.prototype.watchAndDoShow = function() {
if (this.model.show != null) {
this.scope.show = this.model.show;
}
this.scope.$watch('show', this.doShow, true);
return this.doShow();
};
WindowChildModel.prototype.watchElement = function() {
return this.scope.$watch((function(_this) {
return function() {
var ref, wasOpen;
if (!(_this.element || _this.html)) {
return;
}
if (_this.html !== _this.element.html() && _this.gObject) {
if ((ref = _this.opts) != null) {
ref.content = void 0;
}
wasOpen = _this.gObject.isOpen();
_this.remove();
return _this.createGWin(wasOpen);
}
};
})(this));
};
WindowChildModel.prototype.createGWin = function(isOpen) {
var _opts, defaults, maybeMarker, ref, ref1;
if (isOpen == null) {
isOpen = false;
}
maybeMarker = this.getGmarker();
defaults = {};
if (this.opts != null) {
if (this.scope.coords) {
this.opts.position = this.getCoords(this.scope.coords);
}
defaults = this.opts;
}
if (this.element) {
this.html = _.isObject(this.element) ? this.element.html() : this.element;
}
_opts = this.scope.options ? this.scope.options : defaults;
this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts);
if (this.opts != null) {
if (!this.gObject) {
if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) {
this.gObject = new window.InfoBox(this.opts);
} else {
this.gObject = new google.maps.InfoWindow(this.opts);
}
this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() {
return ChromeFixes.maybeRepaint(this.content);
}));
this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) {
return function() {
if (maybeMarker) {
maybeMarker.setAnimation(_this.oldMarkerAnimation);
if (_this.markerIsVisibleAfterWindowClose) {
_.delay(function() {
maybeMarker.setVisible(false);
return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose);
}, 250);
}
}
_this.gObject.close();
_this.model.show = false;
if (_this.scope.closeClick != null) {
return _this.scope.$evalAsync(_this.scope.closeClick());
} else {
return _this.scope.$evalAsync();
}
};
})(this)));
}
this.gObject.setContent(this.opts.content);
this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen);
return this.doShow(this.gObject.isOpen());
}
};
WindowChildModel.prototype.watchCoords = function() {
var scope;
scope = this.markerScope != null ? this.markerScope : this.scope;
return scope.$watch('coords', (function(_this) {
return function(newValue, oldValue) {
var pos;
if (newValue !== oldValue) {
if (newValue == null) {
_this.hideWindow();
} else if (!_this.validateCoords(newValue)) {
$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model)));
return;
}
pos = _this.getCoords(newValue);
_this.gObject.setPosition(pos);
if (_this.opts) {
return _this.opts.position = pos;
}
}
};
})(this), true);
};
WindowChildModel.prototype.watchOptions = function() {
return this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.opts = newValue;
if (_this.gObject != null) {
_this.gObject.setOptions(_this.opts);
if ((_this.opts.visible != null) && _this.opts.visible) {
return _this.showWindow();
} else if (_this.opts.visible != null) {
return _this.hideWindow();
}
}
}
};
})(this), true);
};
WindowChildModel.prototype.handleClick = function(forceClick) {
var click, maybeMarker;
if (this.gObject == null) {
return;
}
maybeMarker = this.getGmarker();
click = (function(_this) {
return function() {
if (_this.gObject == null) {
_this.createGWin();
}
_this.showWindow();
if (maybeMarker != null) {
_this.initialMarkerVisibility = maybeMarker.getVisible();
_this.oldMarkerAnimation = maybeMarker.getAnimation();
return maybeMarker.setVisible(_this.isIconVisibleOnClick);
}
};
})(this);
if (forceClick) {
click();
}
if (maybeMarker) {
return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, {
events: {
click: click
}
}, this.model));
}
};
WindowChildModel.prototype.showWindow = function() {
var compiled, show, templateScope;
if (this.gObject != null) {
show = (function(_this) {
return function() {
var isOpen, maybeMarker, pos;
if (!_this.gObject.isOpen()) {
maybeMarker = _this.getGmarker();
if ((_this.gObject != null) && (_this.gObject.getPosition != null)) {
pos = _this.gObject.getPosition();
}
if (maybeMarker) {
pos = maybeMarker.getPosition();
}
if (!pos) {
return;
}
_this.gObject.open(_this.mapCtrl, maybeMarker);
isOpen = _this.gObject.isOpen();
if (_this.model.show !== isOpen) {
return _this.model.show = isOpen;
}
}
};
})(this);
if (this.scope.templateUrl) {
return $http.get(this.scope.templateUrl, {
cache: $templateCache
}).then((function(_this) {
return function(content) {
var compiled, templateScope;
templateScope = _this.scope.$new();
if (angular.isDefined(_this.scope.templateParameter)) {
templateScope.parameter = _this.scope.templateParameter;
}
compiled = $compile(content.data)(templateScope);
_this.gObject.setContent(compiled[0]);
return show();
};
})(this));
} else if (this.scope.template) {
templateScope = this.scope.$new();
if (angular.isDefined(this.scope.templateParameter)) {
templateScope.parameter = this.scope.templateParameter;
}
compiled = $compile(this.scope.template)(templateScope);
this.gObject.setContent(compiled[0]);
return show();
} else {
return show();
}
}
};
WindowChildModel.prototype.hideWindow = function() {
if ((this.gObject != null) && this.gObject.isOpen()) {
return this.gObject.close();
}
};
WindowChildModel.prototype.getLatestPosition = function(overridePos) {
var maybeMarker;
maybeMarker = this.getGmarker();
if ((this.gObject != null) && (maybeMarker != null) && !overridePos) {
return this.gObject.setPosition(maybeMarker.getPosition());
} else {
if (overridePos) {
return this.gObject.setPosition(overridePos);
}
}
};
WindowChildModel.prototype.remove = function() {
this.hideWindow();
this.removeEvents(this.listeners);
this.listeners.length = 0;
delete this.gObject;
return delete this.opts;
};
WindowChildModel.prototype.destroy = function(manualOverride) {
var ref;
if (manualOverride == null) {
manualOverride = false;
}
this.remove();
if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
}
};
WindowChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return _.extend(this.model, this.clonedModel);
};
return WindowChildModel;
})(BaseObject);
return WindowChildModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise) {
return function(IPoly, PolyChildModel, gObjectName) {
var BasePolysParentModel;
return BasePolysParentModel = (function(superClass) {
extend(BasePolysParentModel, superClass);
BasePolysParentModel.include(ModelsWatcher);
function BasePolysParentModel(scope, element, attrs, gMap1, defaults) {
this.element = element;
this.attrs = attrs;
this.gMap = gMap1;
this.defaults = defaults;
this.createChild = bind(this.createChild, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.createAllNew = bind(this.createAllNew, this);
this.watchIdKey = bind(this.watchIdKey, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.watchDestroy = bind(this.watchDestroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.doINeedToWipe = bind(this.doINeedToWipe, this);
this.watchModels = bind(this.watchModels, this);
BasePolysParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPoly;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPoly.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.createChildScopes();
}
BasePolysParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
BasePolysParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
BasePolysParentModel.prototype.onDestroy = function(scope) {
BasePolysParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var ref;
return (ref = _this.plurals) != null ? ref.removeAll() : void 0;
});
};
})(this));
};
BasePolysParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error("No models to create " + gObjectName + "s from! I Need direct models!");
return;
}
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
BasePolysParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
BasePolysParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var child;
child = _this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
child.isEnabled = false;
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
if (payload.updates.length) {
$log.info("polygons updates: " + payload.updates.length + " will be missed");
}
return _async.each(payload.removals, function(child) {
if (child != null) {
child.destroy();
_this.plurals.remove(child.model[_this.idKey]);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
BasePolysParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(IPoly.scopeKeys, childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolyChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error(gObjectName + " model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
return BasePolysParentModel;
})(ModelKey);
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) {
var CircleParentModel;
return CircleParentModel = (function(superClass) {
extend(CircleParentModel, superClass);
CircleParentModel.include(GmapUtil);
CircleParentModel.include(EventsHelper);
function CircleParentModel(scope, element, attrs, map, DEFAULTS) {
var clean, gObject, lastRadius;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
this.scope = scope;
lastRadius = null;
clean = (function(_this) {
return function() {
lastRadius = null;
if (_this.listeners != null) {
_this.removeEvents(_this.listeners);
return _this.listeners = void 0;
}
};
})(this);
gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
}
};
})(this);
this.props = this.props.concat([
{
prop: 'center',
isColl: true
}, {
prop: 'fill',
isColl: true
}, 'radius', 'zIndex'
]);
this.watchProps();
clean();
this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']);
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() {
/*
possible google bug, and or because a circle has two radii
radius_changed appears to fire twice (original and new) which is not too helpful
therefore we will check for radius changes manually and bail out if nothing has changed
*/
var newRadius, work;
newRadius = gObject.getRadius();
if (newRadius === lastRadius) {
return;
}
lastRadius = newRadius;
work = function() {
var ref, ref1;
if (newRadius !== scope.radius) {
scope.radius = newRadius;
}
if (((ref = scope.events) != null ? ref.radius_changed : void 0) && _.isFunction((ref1 = scope.events) != null ? ref1.radius_changed : void 0)) {
return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments);
}
};
if (!angular.mock) {
return scope.$evalAsync(function() {
return work();
});
} else {
return work();
}
}));
}
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() {
return scope.$evalAsync(function() {
if (angular.isDefined(scope.center.type)) {
scope.center.coordinates[1] = gObject.getCenter().lat();
return scope.center.coordinates[0] = gObject.getCenter().lng();
} else {
scope.center.latitude = gObject.getCenter().lat();
return scope.center.longitude = gObject.getCenter().lng();
}
});
}));
}
scope.$on('$destroy', (function(_this) {
return function() {
clean();
return gObject.setMap(null);
};
})(this));
$log.info(this);
}
return CircleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) {
var DrawingManagerParentModel;
return DrawingManagerParentModel = (function(superClass) {
extend(DrawingManagerParentModel, superClass);
DrawingManagerParentModel.include(EventsHelper);
function DrawingManagerParentModel(scope, element, attrs, map) {
var gObject, listeners;
this.scope = scope;
this.attrs = attrs;
this.map = map;
gObject = new google.maps.drawing.DrawingManager(this.scope.options);
gObject.setMap(this.map);
listeners = void 0;
if (this.scope.control != null) {
this.scope.control.getDrawingManager = function() {
return gObject;
};
}
if (!this.scope["static"] && this.scope.options) {
this.scope.$watch('options', function(newValue) {
return gObject != null ? gObject.setOptions(newValue) : void 0;
}, true);
}
if (this.scope.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
this.scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
this.scope.$on('$destroy', (function(_this) {
return function() {
if (listeners != null) {
_this.removeEvents(listeners);
}
gObject.setMap(null);
return gObject = null;
};
})(this));
}
return DrawingManagerParentModel;
})(BaseObject);
}
]);
}).call(this);
;
/*
- interface for all markers to derrive from
- to enforce a minimum set of requirements
- attributes
- coords
- icon
- implementation needed on watches
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [
"uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) {
var IMarkerParentModel;
IMarkerParentModel = (function(superClass) {
extend(IMarkerParentModel, superClass);
IMarkerParentModel.prototype.DEFAULTS = {};
function IMarkerParentModel(scope1, element, attrs, map) {
this.scope = scope1;
this.element = element;
this.attrs = attrs;
this.map = map;
this.onWatch = bind(this.onWatch, this);
this.watch = bind(this.watch, this);
this.validateScope = bind(this.validateScope, this);
IMarkerParentModel.__super__.constructor.call(this, this.scope);
this.$log = Logger;
if (!this.validateScope(this.scope)) {
throw new String("Unable to construct IMarkerParentModel due to invalid scope");
}
this.doClick = angular.isDefined(this.attrs.click);
if (this.scope.options != null) {
this.DEFAULTS = this.scope.options;
}
this.watch('coords', this.scope);
this.watch('icon', this.scope);
this.watch('options', this.scope);
this.scope.$on("$destroy", (function(_this) {
return function() {
return _this.onDestroy(_this.scope);
};
})(this));
}
IMarkerParentModel.prototype.validateScope = function(scope) {
var ret;
if (scope == null) {
this.$log.error(this.constructor.name + ": invalid scope used");
return false;
}
ret = scope.coords != null;
if (!ret) {
this.$log.error(this.constructor.name + ": no valid coords attribute found");
return false;
}
return ret;
};
IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) {
if (equalityCheck == null) {
equalityCheck = true;
}
return scope.$watch(propNameToWatch, (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.onWatch(propNameToWatch, scope, newValue, oldValue);
}
};
})(this), equalityCheck);
};
IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {};
return IMarkerParentModel;
})(ModelKey);
return IMarkerParentModel;
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [
"uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) {
var IWindowParentModel;
return IWindowParentModel = (function(superClass) {
extend(IWindowParentModel, superClass);
IWindowParentModel.include(GmapUtil);
function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) {
IWindowParentModel.__super__.constructor.call(this, scope);
this.$log = Logger;
this.$timeout = $timeout;
this.$compile = $compile;
this.$http = $http;
this.$templateCache = $templateCache;
this.DEFAULTS = {};
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
}
IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return IWindowParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) {
var LayerParentModel;
LayerParentModel = (function(superClass) {
extend(LayerParentModel, superClass);
function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0;
this.$log = $log != null ? $log : Logger;
this.createGoogleLayer = bind(this.createGoogleLayer, this);
if (this.attrs.type == null) {
this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!');
return;
}
this.createGoogleLayer();
this.doShow = true;
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.gObject.setMap(this.gMap);
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.gObject.setMap(_this.gMap);
} else {
return _this.gObject.setMap(null);
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.gObject.setMap(null);
_this.gObject = null;
return _this.createGoogleLayer();
}
};
})(this), true);
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject.setMap(null);
};
})(this));
}
LayerParentModel.prototype.createGoogleLayer = function() {
var base;
if (this.attrs.options == null) {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type]();
} else {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options);
}
if ((this.gObject != null) && (this.onLayerCreated != null)) {
return typeof (base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? base(this.gObject) : void 0;
}
};
return LayerParentModel;
})(BaseObject);
return LayerParentModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) {
var MapTypeParentModel;
MapTypeParentModel = (function(superClass) {
extend(MapTypeParentModel, superClass);
function MapTypeParentModel(scope, element, attrs, gMap, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.$log = $log != null ? $log : Logger;
this.hideOverlay = bind(this.hideOverlay, this);
this.showOverlay = bind(this.showOverlay, this);
this.refreshMapType = bind(this.refreshMapType, this);
this.createMapType = bind(this.createMapType, this);
if (this.attrs.options == null) {
this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!');
return;
}
this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0;
this.doShow = true;
this.createMapType();
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.showOverlay();
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.showOverlay();
} else {
return _this.hideOverlay();
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
if (angular.isDefined(this.attrs.refresh)) {
this.scope.$watch('refresh', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.hideOverlay();
return _this.mapType = null;
};
})(this));
}
MapTypeParentModel.prototype.createMapType = function() {
if (this.scope.options.getTile != null) {
this.mapType = this.scope.options;
} else if (this.scope.options.getTileUrl != null) {
this.mapType = new google.maps.ImageMapType(this.scope.options);
} else {
this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!');
return;
}
if (this.attrs.id && this.scope.id) {
this.gMap.mapTypes.set(this.scope.id, this.mapType);
if (!angular.isDefined(this.attrs.show)) {
this.doShow = false;
}
}
return this.mapType.layerId = this.id;
};
MapTypeParentModel.prototype.refreshMapType = function() {
this.hideOverlay();
this.mapType = null;
this.createMapType();
if (this.doShow && (this.gMap != null)) {
return this.showOverlay();
}
};
MapTypeParentModel.prototype.showOverlay = function() {
return this.gMap.overlayMapTypes.push(this.mapType);
};
MapTypeParentModel.prototype.hideOverlay = function() {
var found;
found = false;
return this.gMap.overlayMapTypes.forEach((function(_this) {
return function(mapType, index) {
if (!found && mapType.layerId === _this.id) {
found = true;
_this.gMap.overlayMapTypes.removeAt(index);
}
};
})(this));
};
return MapTypeParentModel;
})(BaseObject);
return MapTypeParentModel;
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [
"uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) {
var MarkersParentModel, _setPlurals;
_setPlurals = function(val, objToSet) {
objToSet.plurals = new PropMap();
objToSet.scope.plurals = objToSet.plurals;
return objToSet;
};
MarkersParentModel = (function(superClass) {
extend(MarkersParentModel, superClass);
MarkersParentModel.include(GmapUtil);
MarkersParentModel.include(ModelsWatcher);
function MarkersParentModel(scope, element, attrs, map) {
this.onDestroy = bind(this.onDestroy, this);
this.newChildMarker = bind(this.newChildMarker, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.createAllNew = bind(this.createAllNew, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.validateScope = bind(this.validateScope, this);
this.onWatch = bind(this.onWatch, this);
var self;
MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map);
this["interface"] = IMarker;
self = this;
_setPlurals(new PropMap(), this);
this.scope.pluralsUpdate = {
updateCtr: 0
};
this.$log.info(this);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
this.setIdKey(this.scope);
this.scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
if (!this.modelsLength()) {
this.modelsRendered = false;
}
this.scope.$watch('models', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) {
if (newValue.length === 0 && oldValue.length === 0) {
return;
}
_this.modelsRendered = true;
return _this.onWatch('models', _this.scope, newValue, oldValue);
}
};
})(this), !this.isTrue(attrs.modelsbyref));
this.watch('doCluster', this.scope);
this.watch('clusterOptions', this.scope);
this.watch('clusterEvents', this.scope);
this.watch('fit', this.scope);
this.watch('idKey', this.scope);
this.gManager = void 0;
this.createAllNew(this.scope);
}
MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {
if (propNameToWatch === "idKey" && newValue !== oldValue) {
this.idKey = newValue;
}
if (this.doRebuildAll || propNameToWatch === 'doCluster') {
return this.rebuildAll(scope);
} else {
return this.pieceMeal(scope);
}
};
MarkersParentModel.prototype.validateScope = function(scope) {
var modelsNotDefined;
modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0;
if (modelsNotDefined) {
this.$log.error(this.constructor.name + ": no valid models attribute found");
}
return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined;
};
/*
Not used internally by this parent
created for consistency for external control in the API
*/
MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
MarkersParentModel.prototype.createAllNew = function(scope) {
var maybeCanceled, ref, ref1, ref2, self;
if (this.gManager != null) {
this.gManager.clear();
delete this.gManager;
}
if (scope.doCluster) {
if (scope.clusterEvents) {
self = this;
if (!this.origClusterEvents) {
this.origClusterEvents = {
click: (ref = scope.clusterEvents) != null ? ref.click : void 0,
mouseout: (ref1 = scope.clusterEvents) != null ? ref1.mouseout : void 0,
mouseover: (ref2 = scope.clusterEvents) != null ? ref2.mouseover : void 0
};
} else {
angular.extend(scope.clusterEvents, this.origClusterEvents);
}
angular.extend(scope.clusterEvents, {
click: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'click');
},
mouseout: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseout');
},
mouseover: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseover');
}
});
}
this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents);
} else {
this.gManager = new MarkerManager(this.map);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.newChildMarker(model, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
_this.modelsRendered = true;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
return _this.scope.pluralsUpdate.updateCtr += 1;
}, _async.chunkSizeFrom(scope.chunk));
};
})(this));
};
MarkersParentModel.prototype.rebuildAll = function(scope) {
var ref;
if (!scope.doRebuild && scope.doRebuild !== void 0) {
return;
}
if ((ref = this.scope.plurals) != null ? ref.length : void 0) {
return this.onDestroy(scope).then((function(_this) {
return function() {
return _this.createAllNew(scope);
};
})(this));
} else {
return this.createAllNew(scope);
}
};
MarkersParentModel.prototype.pieceMeal = function(scope) {
var maybeCanceled, payload;
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if (this.modelsLength() && this.scope.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
if (child.destroy != null) {
child.destroy();
}
_this.scope.plurals.remove(child.id);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
_this.newChildMarker(modelToAdd, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) {
scope.plurals = _this.scope.plurals;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(scope);
}
};
MarkersParentModel.prototype.newChildMarker = function(model, scope) {
var child, childScope, doDrawSelf, keys;
if (model[this.idKey] == null) {
this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
this.$log.info('child', child, 'markers', this.scope.plurals);
childScope = scope.$new(true);
childScope.events = scope.events;
keys = {};
IMarker.scopeKeys.forEach(function(k) {
return keys[k] = scope[k];
});
child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false);
this.scope.plurals.put(model[this.idKey], child);
return child;
};
MarkersParentModel.prototype.onDestroy = function(scope) {
MarkersParentModel.__super__.onDestroy.call(this, scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.scope.plurals.values(), function(model) {
if (model != null) {
return model.destroy(false);
}
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (_this.gManager != null) {
_this.gManager.clear();
}
_this.plurals.removeAll();
if (_this.plurals !== _this.scope.plurals) {
console.error('plurals out of sync for MarkersParentModel');
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
};
MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) {
var pair, ref;
if (_.isFunction((ref = this.scope.clusterEvents) != null ? ref[fnName] : void 0)) {
pair = this.mapClusterToPlurals(cluster);
if (this.origClusterEvents[fnName]) {
return this.origClusterEvents[fnName](pair.cluster, pair.mapped);
}
}
};
MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) {
var mapped;
mapped = cluster.getMarkers().map((function(_this) {
return function(g) {
return _this.scope.plurals.get(g.key).model;
};
})(this));
return {
cluster: cluster,
mapped: mapped
};
};
MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return MarkersParentModel;
})(IMarkerParentModel);
return MarkersParentModel;
}
]);
}).call(this);
;(function() {
['Polygon', 'Polyline'].forEach(function(name) {
return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory("uiGmap" + name + "sParentModel", [
'uiGmapBasePolysParentModel', "uiGmap" + name + "ChildModel", "uiGmapI" + name, function(BasePolysParentModel, ChildModel, IPoly) {
return BasePolysParentModel(IPoly, ChildModel, name);
}
]);
});
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) {
var RectangleParentModel;
return RectangleParentModel = (function(superClass) {
extend(RectangleParentModel, superClass);
RectangleParentModel.include(GmapUtil);
RectangleParentModel.include(EventsHelper);
function RectangleParentModel(scope, element, attrs, map, DEFAULTS) {
var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
bounds = void 0;
dragging = false;
myListeners = [];
listeners = void 0;
fit = (function(_this) {
return function() {
if (_this.isTrue(_this.attrs.fit)) {
return _this.fitMapBounds(_this.map, bounds);
}
};
})(this);
createBounds = (function(_this) {
return function() {
var ref, ref1, ref2;
if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) {
bounds = _this.convertBoundPoints(_this.scope.bounds);
return $log.info("new new bounds created: " + (JSON.stringify(bounds)));
} else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) {
return bounds = _this.scope.bounds;
} else {
if (_this.scope.bounds != null) {
return $log.error("Invalid bounds for newValue: " + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0)));
}
}
};
})(this);
createBounds();
gObject = new google.maps.Rectangle(this.buildOpts(bounds));
$log.info("gObject (rectangle) created: " + gObject);
settingBoundsFromScope = false;
updateBounds = (function(_this) {
return function() {
var b, ne, sw;
b = gObject.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
if (settingBoundsFromScope) {
return;
}
return _this.scope.$evalAsync(function(s) {
if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) {
s.bounds.ne = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.sw = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) {
return s.bounds = b;
}
});
};
})(this);
init = (function(_this) {
return function() {
fit();
_this.removeEvents(myListeners);
myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() {
return dragging = true;
}));
myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() {
dragging = false;
return updateBounds();
}));
return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() {
if (dragging) {
return;
}
return updateBounds();
}));
};
})(this);
clear = (function(_this) {
return function() {
_this.removeEvents(myListeners);
if (listeners != null) {
_this.removeEvents(listeners);
}
return gObject.setMap(null);
};
})(this);
if (bounds != null) {
init();
}
this.scope.$watch('bounds', (function(newValue, oldValue) {
var isNew;
if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) {
return;
}
settingBoundsFromScope = true;
if (newValue == null) {
clear();
return;
}
if (bounds == null) {
isNew = true;
} else {
fit();
}
createBounds();
gObject.setBounds(bounds);
settingBoundsFromScope = false;
if (isNew && (bounds != null)) {
return init();
}
}), true);
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
if ((bounds != null) && (newVals != null)) {
return gObject.setOptions(_this.buildOpts(bounds));
}
}
};
})(this);
this.props.push('bounds');
this.watchProps(this.props);
if (this.attrs.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
this.scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return clear();
};
})(this));
$log.info(this);
}
return RectangleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) {
var SearchBoxParentModel;
SearchBoxParentModel = (function(superClass) {
extend(SearchBoxParentModel, superClass);
SearchBoxParentModel.include(EventsHelper);
function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) {
var controlDiv;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.ctrlPosition = ctrlPosition;
this.template = template;
this.$log = $log != null ? $log : Logger;
this.setVisibility = bind(this.setVisibility, this);
this.getBounds = bind(this.getBounds, this);
this.setBounds = bind(this.setBounds, this);
this.createSearchBox = bind(this.createSearchBox, this);
this.addToParentDiv = bind(this.addToParentDiv, this);
this.addAsMapControl = bind(this.addAsMapControl, this);
this.init = bind(this.init, this);
if (this.attrs.template == null) {
this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!');
return;
}
if (angular.isUndefined(this.scope.options)) {
this.scope.options = {};
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.visible)) {
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.autocomplete)) {
this.scope.options.autocomplete = false;
}
this.visible = this.scope.options.visible;
this.autocomplete = this.scope.options.autocomplete;
controlDiv = angular.element('<div></div>');
controlDiv.append(this.template);
this.input = controlDiv.find('input')[0];
this.init();
}
SearchBoxParentModel.prototype.init = function() {
this.createSearchBox();
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (angular.isObject(newValue)) {
if (newValue.bounds != null) {
_this.setBounds(newValue.bounds);
}
if (newValue.visible != null) {
if (_this.visible !== newValue.visible) {
return _this.setVisibility(newValue.visible);
}
}
}
};
})(this), true);
if (this.attrs.parentdiv != null) {
this.addToParentDiv();
} else {
this.addAsMapControl();
}
if (this.autocomplete) {
this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlace();
};
})(this));
} else {
this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlaces();
};
})(this));
}
this.listeners = this.setEvents(this.gObject, this.scope, this.scope);
this.$log.info(this);
return this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject = null;
};
})(this));
};
SearchBoxParentModel.prototype.addAsMapControl = function() {
return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
};
SearchBoxParentModel.prototype.addToParentDiv = function() {
this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv));
return this.parentDiv.append(this.input);
};
SearchBoxParentModel.prototype.createSearchBox = function() {
if (this.autocomplete) {
return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options);
} else {
return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options);
}
};
SearchBoxParentModel.prototype.setBounds = function(bounds) {
if (angular.isUndefined(bounds.isEmpty)) {
this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.');
} else {
if (bounds.isEmpty() === false) {
if (this.gObject != null) {
return this.gObject.setBounds(bounds);
}
}
}
};
SearchBoxParentModel.prototype.getBounds = function() {
return this.gObject.getBounds();
};
SearchBoxParentModel.prototype.setVisibility = function(val) {
if (this.attrs.parentdiv != null) {
if (val === false) {
this.parentDiv.addClass("ng-hide");
} else {
this.parentDiv.removeClass("ng-hide");
}
} else {
if (val === false) {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear();
} else {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
}
}
return this.visible = val;
};
return SearchBoxParentModel;
})(BaseObject);
return SearchBoxParentModel;
}
]);
}).call(this);
;
/*
WindowsChildModel generator where there are many ChildModels to a parent.
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [
'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) {
var WindowsParentModel;
WindowsParentModel = (function(superClass) {
extend(WindowsParentModel, superClass);
WindowsParentModel.include(ModelsWatcher);
function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) {
this.gMap = gMap1;
this.markersScope = markersScope;
this.modelKeyComparison = bind(this.modelKeyComparison, this);
this.interpolateContent = bind(this.interpolateContent, this);
this.setChildScope = bind(this.setChildScope, this);
this.createWindow = bind(this.createWindow, this);
this.setContentKeys = bind(this.setContentKeys, this);
this.pieceMeal = bind(this.pieceMeal, this);
this.createAllNew = bind(this.createAllNew, this);
this.watchIdKey = bind(this.watchIdKey, this);
this.createChildScopes = bind(this.createChildScopes, this);
this.watchOurScope = bind(this.watchOurScope, this);
this.watchDestroy = bind(this.watchDestroy, this);
this.onDestroy = bind(this.onDestroy, this);
this.rebuildAll = bind(this.rebuildAll, this);
this.doINeedToWipe = bind(this.doINeedToWipe, this);
this.watchModels = bind(this.watchModels, this);
this.go = bind(this.go, this);
WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache);
this["interface"] = IWindow;
this.plurals = new PropMap();
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.linked = new Linked(scope, element, attrs, ctrls);
this.contentKeys = void 0;
this.isIconVisibleOnClick = void 0;
this.firstTime = true;
this.firstWatchModels = true;
this.$log.info(self);
this.parentScope = void 0;
this.go(scope);
}
WindowsParentModel.prototype.go = function(scope) {
this.watchOurScope(scope);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
return this.createChildScopes();
};
WindowsParentModel.prototype.watchModels = function(scope) {
var itemToWatch;
itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models';
return scope.$watch(itemToWatch, (function(_this) {
return function(newValue, oldValue) {
var doScratch;
if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) {
_this.firstWatchModels = false;
if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) {
return _this.rebuildAll(scope, true, true);
} else {
doScratch = _this.plurals.length === 0;
if (_this.existingPieces != null) {
return _.last(_this.existingPieces._content).then(function() {
return _this.createChildScopes(doScratch);
});
} else {
return _this.createChildScopes(doScratch);
}
}
}
};
})(this), true);
};
WindowsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
WindowsParentModel.prototype.onDestroy = function(scope) {
WindowsParentModel.__super__.onDestroy.call(this, this.scope);
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy();
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
var ref;
return (ref = _this.plurals) != null ? ref.removeAll() : void 0;
});
};
})(this));
};
WindowsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
_this.firstWatchModels = true;
_this.firstTime = true;
return _this.rebuildAll(scope, false, true);
};
})(this));
};
WindowsParentModel.prototype.watchOurScope = function(scope) {
return _.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
};
})(this));
};
WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
var modelsNotDefined, ref, ref1;
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
/*
being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl)
we will assume that all scope values are string expressions either pointing to a key (propName) or using
'self' to point the model as container/object of interest.
This may force redundant information into the model, but this appears to be the most flexible approach.
*/
this.isIconVisibleOnClick = true;
if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) {
this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick;
}
modelsNotDefined = angular.isUndefined(this.linked.scope.models);
if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) {
this.$log.error('No models to create windows from! Need direct models or models derived from markers!');
return;
}
if (this.gMap != null) {
if (this.linked.scope.models != null) {
this.watchIdKey(this.linked.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.linked.scope, false);
} else {
return this.pieceMeal(this.linked.scope, false);
}
} else {
this.parentScope = this.markersScope;
this.watchIdKey(this.parentScope);
if (isCreatingFromScratch) {
return this.createAllNew(this.markersScope, true, 'plurals', false);
} else {
return this.pieceMeal(this.markersScope, true, 'plurals', false);
}
}
}
};
WindowsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = false;
}
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
this.setContentKeys(scope.models);
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var gMarker, ref;
gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0;
if (!maybeCanceled) {
if (!gMarker && _this.markersScope) {
$log.error('Unable to get gMarker from markersScope!');
}
_this.createWindow(model, gMarker, _this.gMap);
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled, payload;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if ((scope != null) && this.modelsLength() && this.plurals.length) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
_this.plurals.remove(child.id);
if (child.destroy != null) {
child.destroy(true);
}
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
var gMarker, ref;
gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0;
if (!gMarker) {
throw 'Gmarker undefined';
}
_this.createWindow(modelToAdd, gMarker, _this.gMap);
return maybeCanceled;
});
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
$log.debug('pieceMeal: rebuildAll');
return this.rebuildAll(this.scope, true, true);
}
};
WindowsParentModel.prototype.setContentKeys = function(models) {
if (this.modelsLength(models)) {
return this.contentKeys = Object.keys(models[0]);
}
};
WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) {
var child, childScope, fakeElement, opts, ref, ref1;
childScope = this.linked.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
fakeElement = {
html: (function(_this) {
return function() {
return _this.interpolateContent(_this.linked.element.html(), model);
};
})(this)
};
this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {};
opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS);
child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (ref = this.markersScope) != null ? (ref1 = ref.plurals.get(model[this.idKey])) != null ? ref1.scope : void 0 : void 0, fakeElement, false, true);
if (model[this.idKey] == null) {
this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.');
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
WindowsParentModel.prototype.setChildScope = function(childScope, model) {
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
WindowsParentModel.prototype.interpolateContent = function(content, model) {
var exp, i, interpModel, key, len, ref;
if (this.contentKeys === void 0 || this.contentKeys.length === 0) {
return;
}
exp = $interpolate(content);
interpModel = {};
ref = this.contentKeys;
for (i = 0, len = ref.length; i < len; i++) {
key = ref[i];
interpModel[key] = model[key];
}
return exp(interpModel);
};
WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) {
var isEqual, scope;
scope = this.scope.coords != null ? this.scope : this.parentScope;
if (scope == null) {
throw 'No scope or parentScope set!';
}
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
return WindowsParentModel;
})(IWindowParentModel);
return WindowsParentModel;
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [
"uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) {
return _.extend(ICircle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new CircleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [
"uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) {
var Control;
return Control = (function(superClass) {
extend(Control, superClass);
function Control() {
this.link = bind(this.link, this);
Control.__super__.constructor.call(this);
}
Control.prototype.link = function(scope, element, attrs, ctrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
var index, position;
if (angular.isUndefined(scope.template)) {
_this.$log.error('mapControl: could not find a valid template property');
return;
}
index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0;
position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER';
if (!maps.ControlPosition[position]) {
_this.$log.error('mapControl: invalid position property');
return;
}
return IControl.mapPromise(scope, ctrl).then(function(map) {
var control, controlDiv;
control = void 0;
controlDiv = angular.element('<div></div>');
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
var templateCtrl, templateScope;
templateScope = scope.$new();
controlDiv.append(template);
if (angular.isDefined(scope.controller)) {
templateCtrl = $controller(scope.controller, {
$scope: templateScope
});
controlDiv.children().data('$ngControllerController', templateCtrl);
}
control = $compile(controlDiv.children())(templateScope);
if (index) {
return control[0].index = index;
}
}).error(function(error) {
return _this.$log.error('mapControl: template could not be found');
}).then(function() {
return map.controls[google.maps.ControlPosition[position]].push(control[0]);
});
});
};
})(this));
};
return Control;
})(IControl);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) {
return {
restrict: 'EMA',
transclude: true,
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>',
require: '^' + 'uiGmapGoogleMap',
scope: {
keyboardkey: '=',
options: '=',
spec: '='
},
controller: [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'uiGmapDragZoom';
return _.extend(this, CtrlHandle.handle($scope, $element));
}
],
link: function(scope, element, attrs, ctrl) {
return CtrlHandle.mapPromise(scope, ctrl).then(function(map) {
var enableKeyDragZoom, setKeyAction, setOptionsAction;
enableKeyDragZoom = function(opts) {
map.enableKeyDragZoom(opts);
if (scope.spec) {
return scope.spec.enableKeyDragZoom(opts);
}
};
setKeyAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom({
key: newVal
});
} else {
return enableKeyDragZoom();
}
});
setOptionsAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom(newVal);
}
});
scope.$watch('keyboardkey', setKeyAction.sic);
setKeyAction.sic(scope.keyboardkey);
scope.$watch('options', setOptionsAction.sic);
return setOptionsAction.sic(scope.options);
});
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [
"uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) {
return _.extend(IDrawingManager, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then(function(map) {
return new DrawingManagerParentModel(scope, element, attrs, map);
});
}
});
}
]);
}).call(this);
;
/*
- Link up Polygons to be sent back to a controller
- inject the draw function into a controllers scope so that controller can call the directive to draw on demand
- draw function creates the DrawFreeHandChildModel which manages itself
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [
'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) {
var FreeDrawPolygons;
return FreeDrawPolygons = (function(superClass) {
extend(FreeDrawPolygons, superClass);
function FreeDrawPolygons() {
this.link = bind(this.link, this);
return FreeDrawPolygons.__super__.constructor.apply(this, arguments);
}
FreeDrawPolygons.include(CtrlHandle);
FreeDrawPolygons.prototype.restrict = 'EMA';
FreeDrawPolygons.prototype.replace = true;
FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap';
FreeDrawPolygons.prototype.scope = {
polygons: '=',
draw: '=',
revertmapoptions: '='
};
FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) {
return this.mapPromise(scope, ctrl).then((function(_this) {
return function(map) {
var freeHand, listener;
if (!scope.polygons) {
return $log.error('No polygons to bind to!');
}
if (!_.isArray(scope.polygons)) {
return $log.error('Free Draw Polygons must be of type Array!');
}
freeHand = new DrawFreeHandChildModel(map, scope.revertmapoptions);
listener = void 0;
return scope.draw = function() {
if (typeof listener === "function") {
listener();
}
return freeHand.engage(scope.polygons).then(function() {
var firstTime;
firstTime = true;
return listener = scope.$watchCollection('polygons', function(newValue, oldValue) {
var removals;
if (firstTime || newValue === oldValue) {
firstTime = false;
return;
}
removals = uiGmapLodash.differenceObjects(oldValue, newValue);
return removals.forEach(function(p) {
return p.setMap(null);
});
});
});
};
};
})(this));
};
return FreeDrawPolygons;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [
function() {
var DEFAULTS;
DEFAULTS = {};
return {
restrict: "EA",
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
center: "=center",
radius: "=radius",
stroke: "=stroke",
fill: "=fill",
clickable: "=",
draggable: "=",
editable: "=",
geodesic: "=",
icons: "=icons",
visible: "=",
events: "=",
zIndex: "=zindex"
}
};
}
]);
}).call(this);
;
/*
- interface for all controls to derive from
- to enforce a minimum set of requirements
- attributes
- template
- position
- controller
- index
*/
(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [
"uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) {
var IControl;
return IControl = (function(superClass) {
extend(IControl, superClass);
IControl.extend(CtrlHandle);
function IControl() {
this.restrict = 'EA';
this.replace = true;
this.require = '^' + 'uiGmapGoogleMap';
this.scope = {
template: '@template',
position: '@position',
controller: '@controller',
index: '@index'
};
this.$log = Logger;
}
IControl.prototype.link = function(scope, element, attrs, ctrl) {
throw new Exception("Not implemented!!");
};
return IControl;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [
function() {
return {
restrict: 'EA',
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
"static": '@',
control: '=',
options: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [
'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) {
var IMarker;
return IMarker = (function(superClass) {
extend(IMarker, superClass);
IMarker.scope = {
coords: '=coords',
icon: '=icon',
click: '&click',
options: '=options',
events: '=events',
fit: '=fit',
idKey: '=idkey',
control: '=control'
};
IMarker.scopeKeys = _.keys(IMarker.scope);
IMarker.keys = IMarker.scopeKeys;
IMarker.extend(CtrlHandle);
function IMarker() {
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.replace = true;
this.scope = _.extend(this.scope || {}, IMarker.scope);
}
return IMarker;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolygon;
return IPolygon = (function(superClass) {
extend(IPolygon, superClass);
IPolygon.scope = {
path: '=path',
stroke: '=stroke',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
fill: '=',
icons: '=icons',
visible: '=',
"static": '=',
events: '=',
zIndex: '=zindex',
fit: '=',
control: '=control'
};
IPolygon.scopeKeys = _.keys(IPolygon.scope);
IPolygon.include(GmapUtil);
IPolygon.extend(CtrlHandle);
function IPolygon() {}
IPolygon.prototype.restrict = 'EMA';
IPolygon.prototype.replace = true;
IPolygon.prototype.require = '^' + 'uiGmapGoogleMap';
IPolygon.prototype.scope = IPolygon.scope;
IPolygon.prototype.DEFAULTS = {};
IPolygon.prototype.$log = Logger;
return IPolygon;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolyline;
return IPolyline = (function(superClass) {
extend(IPolyline, superClass);
IPolyline.scope = {
path: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
icons: '=',
visible: '=',
"static": '=',
fit: '=',
events: '=',
zIndex: '=zindex'
};
IPolyline.scopeKeys = _.keys(IPolyline.scope);
IPolyline.include(GmapUtil);
IPolyline.extend(CtrlHandle);
function IPolyline() {}
IPolyline.prototype.restrict = 'EMA';
IPolyline.prototype.replace = true;
IPolyline.prototype.require = '^' + 'uiGmapGoogleMap';
IPolyline.prototype.scope = IPolyline.scope;
IPolyline.prototype.DEFAULTS = {};
IPolyline.prototype.$log = Logger;
return IPolyline;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [
function() {
'use strict';
var DEFAULTS;
DEFAULTS = {};
return {
restrict: 'EMA',
require: '^' + 'uiGmapGoogleMap',
replace: true,
scope: {
bounds: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
fill: '=',
visible: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [
'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) {
var IWindow;
return IWindow = (function(superClass) {
extend(IWindow, superClass);
IWindow.scope = {
coords: '=coords',
template: '=template',
templateUrl: '=templateurl',
templateParameter: '=templateparameter',
isIconVisibleOnClick: '=isiconvisibleonclick',
closeClick: '&closeclick',
options: '=options',
control: '=control',
show: '=show'
};
IWindow.scopeKeys = _.keys(IWindow.scope);
IWindow.include(ChildEvents);
IWindow.extend(CtrlHandle);
function IWindow() {
this.restrict = 'EMA';
this.template = void 0;
this.transclude = true;
this.priority = -100;
this.require = '^' + 'uiGmapGoogleMap';
this.replace = true;
this.scope = _.extend(this.scope || {}, IWindow.scope);
}
return IWindow;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [
'$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) {
'use strict';
var DEFAULTS, Map, initializeItems;
DEFAULTS = void 0;
initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer];
return Map = (function(superClass) {
extend(Map, superClass);
Map.include(GmapUtil);
function Map() {
this.link = bind(this.link, this);
var ctrlFn, self;
ctrlFn = function($scope) {
var ctrlObj, retCtrl;
retCtrl = void 0;
$scope.$on('$destroy', function() {
return IsReady.decrement();
});
ctrlObj = CtrlHandle.handle($scope);
$scope.ctrlType = 'Map';
$scope.deferred.promise.then(function() {
return initializeItems.forEach(function(i) {
return i.init();
});
});
ctrlObj.getMap = function() {
return $scope.map;
};
retCtrl = _.extend(this, ctrlObj);
return retCtrl;
};
this.controller = ['$scope', ctrlFn];
self = this;
}
Map.prototype.restrict = 'EMA';
Map.prototype.transclude = true;
Map.prototype.replace = false;
Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>';
Map.prototype.scope = {
center: '=',
zoom: '=',
dragging: '=',
control: '=',
options: '=',
events: '=',
eventOpts: '=',
styles: '=',
bounds: '=',
update: '='
};
Map.prototype.link = function(scope, element, attrs) {
var listeners, unbindCenterWatch;
listeners = [];
scope.$on('$destroy', function() {
return EventsHelper.removeEvents(listeners);
});
scope.idleAndZoomChanged = false;
if (scope.center == null) {
unbindCenterWatch = scope.$watch('center', (function(_this) {
return function() {
if (!scope.center) {
return;
}
unbindCenterWatch();
return _this.link(scope, element, attrs);
};
})(this));
return;
}
return GoogleMapApi.then((function(_this) {
return function(maps) {
var _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise;
DEFAULTS = {
mapTypeId: maps.MapTypeId.ROADMAP
};
spawned = IsReady.spawn();
resolveSpawned = function() {
return spawned.deferred.resolve({
instance: spawned.instance,
map: _gMap
});
};
if (!_this.validateCoords(scope.center)) {
$log.error('angular-google-maps: could not find a valid center property');
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error('angular-google-maps: map zoom property not set');
return;
}
el = angular.element(element);
el.addClass('angular-google-map');
opts = {
options: {}
};
if (attrs.options) {
opts.options = scope.options;
}
if (attrs.styles) {
opts.styles = scope.styles;
}
if (attrs.type) {
type = attrs.type.toUpperCase();
if (google.maps.MapTypeId.hasOwnProperty(type)) {
opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()];
} else {
$log.error("angular-google-maps: invalid map type '" + attrs.type + "'");
}
}
mapOptions = angular.extend({}, DEFAULTS, opts, {
center: _this.getCoords(scope.center),
zoom: scope.zoom,
bounds: scope.bounds
});
_gMap = new google.maps.Map(el.find('div')[1], mapOptions);
_gMap['uiGmap_id'] = uuid.generate();
dragging = false;
listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() {
scope.deferred.resolve(_gMap);
return resolveSpawned();
}));
disabledEvents = attrs.events && (((ref = scope.events) != null ? ref.blacklist : void 0) != null) ? scope.events.blacklist : [];
if (_.isString(disabledEvents)) {
disabledEvents = [disabledEvents];
}
maybeHookToEvent = function(eventName, fn, prefn) {
if (!_.contains(disabledEvents, eventName)) {
if (prefn) {
prefn();
}
return listeners.push(google.maps.event.addListener(_gMap, eventName, function() {
var ref1;
if (!((ref1 = scope.update) != null ? ref1.lazy : void 0)) {
return fn();
}
}));
}
};
if (!_.contains(disabledEvents, 'all')) {
maybeHookToEvent('dragstart', function() {
dragging = true;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
maybeHookToEvent('dragend', function() {
dragging = false;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
updateCenter = function(c, s) {
if (c == null) {
c = _gMap.center;
}
if (s == null) {
s = scope;
}
if (_.contains(disabledEvents, 'center')) {
return;
}
if (angular.isDefined(s.center.type)) {
if (s.center.coordinates[1] !== c.lat()) {
s.center.coordinates[1] = c.lat();
}
if (s.center.coordinates[0] !== c.lng()) {
return s.center.coordinates[0] = c.lng();
}
} else {
if (s.center.latitude !== c.lat()) {
s.center.latitude = c.lat();
}
if (s.center.longitude !== c.lng()) {
return s.center.longitude = c.lng();
}
}
};
settingFromDirective = false;
maybeHookToEvent('idle', function() {
var b, ne, sw;
b = _gMap.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
settingFromDirective = true;
return scope.$evalAsync(function(s) {
updateCenter();
if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) {
s.bounds.northeast = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.southwest = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if (!_.contains(disabledEvents, 'zoom')) {
s.zoom = _gMap.zoom;
scope.idleAndZoomChanged = !scope.idleAndZoomChanged;
}
return settingFromDirective = false;
});
});
}
if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) {
getEventHandler = function(eventName) {
return function() {
return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]);
};
};
customListeners = [];
for (eventName in scope.events) {
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) {
customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName)));
}
}
listeners.concat(customListeners);
}
_gMap.getOptions = function() {
return mapOptions;
};
scope.map = _gMap;
if ((attrs.control != null) && (scope.control != null)) {
scope.control.refresh = function(maybeCoords) {
var coords, ref1, ref2;
if (_gMap == null) {
return;
}
if (((typeof google !== "undefined" && google !== null ? (ref1 = google.maps) != null ? (ref2 = ref1.event) != null ? ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) {
google.maps.event.trigger(_gMap, 'resize');
}
if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) {
coords = _this.getCoords(maybeCoords);
if (_this.isTrue(attrs.pan)) {
return _gMap.panTo(coords);
} else {
return _gMap.setCenter(coords);
}
}
};
scope.control.getGMap = function() {
return _gMap;
};
scope.control.getMapOptions = function() {
return mapOptions;
};
scope.control.getCustomEventListeners = function() {
return customListeners;
};
scope.control.removeEvents = function(yourListeners) {
return EventsHelper.removeEvents(yourListeners);
};
}
scope.$watch('center', function(newValue, oldValue) {
var coords, settingCenterFromScope;
if (newValue === oldValue || settingFromDirective) {
return;
}
coords = _this.getCoords(scope.center);
if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) {
return;
}
settingCenterFromScope = true;
if (!dragging) {
if (!_this.validateCoords(newValue)) {
$log.error("Invalid center for newValue: " + (JSON.stringify(newValue)));
}
if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) {
_gMap.panTo(coords);
} else {
_gMap.setCenter(coords);
}
}
return settingCenterFromScope = false;
}, true);
zoomPromise = null;
scope.$watch('zoom', function(newValue, oldValue) {
var ref1, ref2, settingZoomFromScope;
if (newValue == null) {
return;
}
if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) {
return;
}
settingZoomFromScope = true;
if (zoomPromise != null) {
$timeout.cancel(zoomPromise);
}
return zoomPromise = $timeout(function() {
_gMap.setZoom(newValue);
return settingZoomFromScope = false;
}, ((ref1 = scope.eventOpts) != null ? (ref2 = ref1.debounce) != null ? ref2.zoomMs : void 0 : void 0) + 20, false);
});
scope.$watch('bounds', function(newValue, oldValue) {
var bounds, ne, ref1, ref2, ref3, ref4, sw;
if (newValue === oldValue) {
return;
}
if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) {
$log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue)));
return;
}
ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude);
sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude);
bounds = new google.maps.LatLngBounds(sw, ne);
return _gMap.fitBounds(bounds);
});
return ['options', 'styles'].forEach(function(toWatch) {
return scope.$watch(toWatch, function(newValue, oldValue) {
var watchItem;
watchItem = this.exp;
if (_.isEqual(newValue, oldValue)) {
return;
}
if (watchItem === 'options') {
opts.options = newValue;
} else {
opts.options[watchItem] = newValue;
}
if (_gMap != null) {
return _gMap.setOptions(opts);
}
}, true);
});
};
})(this));
};
return Map;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [
"uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) {
var Marker;
return Marker = (function(superClass) {
extend(Marker, superClass);
function Marker() {
this.link = bind(this.link, this);
Marker.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-marker" ng-transclude></span>';
$log.info(this);
}
Marker.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Marker';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Marker.prototype.link = function(scope, element, attrs, ctrl) {
var mapPromise;
mapPromise = IMarker.mapPromise(scope, ctrl);
mapPromise.then((function(_this) {
return function(map) {
var doClick, doDrawSelf, gManager, keys, m, trackModel;
gManager = new MarkerManager(map);
keys = _.object(IMarker.keys, IMarker.keys);
m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false);
m.deferred.promise.then(function(gMarker) {
return scope.deferred.resolve(gMarker);
});
if (scope.control != null) {
return scope.control.getGMarkers = gManager.getGMarkers;
}
};
})(this));
return scope.$on('$destroy', (function(_this) {
return function() {
var gManager;
if (typeof gManager !== "undefined" && gManager !== null) {
gManager.clear();
}
return gManager = null;
};
})(this));
};
return Marker;
})(IMarker);
}
]);
}).call(this);
;(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [
"uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) {
var Markers;
return Markers = (function(superClass) {
extend(Markers, superClass);
function Markers() {
Markers.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-markers" ng-transclude></span>';
Plural.extend(this, {
doCluster: '=docluster',
clusterOptions: '=clusteroptions',
clusterEvents: '=clusterevents',
modelsByRef: '=modelsbyref'
});
$log.info(this);
}
Markers.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Markers';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Markers.prototype.link = function(scope, element, attrs, ctrl) {
var parentModel, ready;
parentModel = void 0;
ready = function() {
return scope.deferred.resolve();
};
return IMarker.mapPromise(scope, ctrl).then(function(map) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.$watch('idleAndZoomChanged', function() {
return _.defer(parentModel.gManager.draw);
});
parentModel = new MarkersParentModel(scope, element, attrs, map);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGMarkers = function() {
var ref;
return (ref = parentModel.gManager) != null ? ref.getGMarkers() : void 0;
};
scope.control.getChildMarkers = function() {
return parentModel.plurals;
};
}
return _.last(parentModel.existingPieces._content).then(function() {
return ready();
});
});
};
return Markers;
})(IMarker);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [
function() {
var _initControl;
_initControl = function(scope, parent) {
if (scope.control == null) {
return;
}
scope.control.updateModels = function(models) {
scope.models = models;
return parent.createChildScopes(false);
};
scope.control.newModels = function(models) {
scope.models = models;
return parent.rebuildAll(scope, true, true);
};
scope.control.clean = function() {
return parent.rebuildAll(scope, false, true);
};
scope.control.getPlurals = function() {
return parent.plurals;
};
scope.control.getManager = function() {
return parent.gManager;
};
scope.control.hasManager = function() {
return (parent.gManager != null) === true;
};
return scope.control.managerDraw = function() {
var ref;
if (scope.control.hasManager()) {
return (ref = scope.control.getManager()) != null ? ref.draw() : void 0;
}
};
};
return {
extend: function(obj, obj2) {
return _.extend(obj.scope || {}, obj2 || {}, {
idKey: '=idkey',
doRebuildAll: '=dorebuildall',
models: '=models',
chunk: '=chunk',
cleanchunk: '=cleanchunk',
control: '=control'
});
},
link: function(scope, parent) {
return _initControl(scope, parent);
}
};
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) {
var Polygon;
return Polygon = (function(superClass) {
extend(Polygon, superClass);
function Polygon() {
this.link = bind(this.link, this);
return Polygon.__super__.constructor.apply(this, arguments);
}
Polygon.prototype.link = function(scope, element, attrs, mapCtrl) {
var children, promise;
children = [];
promise = IPolygon.mapPromise(scope, mapCtrl);
if (scope.control != null) {
scope.control.getInstance = this;
scope.control.polygons = children;
scope.control.promise = promise;
}
return promise.then((function(_this) {
return function(map) {
return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygon;
})(IPolygon);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) {
var Polygons;
return Polygons = (function(superClass) {
extend(Polygons, superClass);
function Polygons() {
this.link = bind(this.link, this);
Polygons.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polygons.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polygons: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polygons: no models found to create from');
}
return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygons;
})(Interface);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) {
var Polyline;
return Polyline = (function(superClass) {
extend(Polyline, superClass);
function Polyline() {
this.link = bind(this.link, this);
return Polyline.__super__.constructor.apply(this, arguments);
}
Polyline.prototype.link = function(scope, element, attrs, mapCtrl) {
return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) {
_this.$log.warn('polyline: no valid path attribute found');
}
return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS);
};
})(this));
};
return Polyline;
})(IPolyline);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) {
var Polylines;
return Polylines = (function(superClass) {
extend(Polylines, superClass);
function Polylines() {
this.link = bind(this.link, this);
Polylines.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polylines.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polylines: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polylines: no models found to create from');
}
return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polylines;
})(IPolyline);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) {
return _.extend(IRectangle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new RectangleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [
'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) {
var Window;
return Window = (function(superClass) {
extend(Window, superClass);
Window.include(GmapUtil);
function Window() {
this.link = bind(this.link, this);
Window.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker'];
this.template = '<span class="angular-google-maps-window" ng-transclude></span>';
$log.debug(this);
this.childWindows = [];
}
Window.prototype.link = function(scope, element, attrs, ctrls) {
var markerCtrl, markerScope;
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
this.mapPromise = IWindow.mapPromise(scope, ctrls[0]);
return this.mapPromise.then((function(_this) {
return function(mapCtrl) {
var isIconVisibleOnClick;
isIconVisibleOnClick = true;
if (angular.isDefined(attrs.isiconvisibleonclick)) {
isIconVisibleOnClick = scope.isIconVisibleOnClick;
}
if (!markerCtrl) {
_this.init(scope, element, isIconVisibleOnClick, mapCtrl);
return;
}
return markerScope.deferred.promise.then(function(gMarker) {
return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope);
});
};
})(this));
};
Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) {
var childWindow, defaults, gMarker, hasScopeCoords, opts;
defaults = scope.options != null ? scope.options : {};
hasScopeCoords = (scope != null) && this.validateCoords(scope.coords);
if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) {
gMarker = markerScope.getGMarker();
}
opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults;
if (mapCtrl != null) {
childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element);
this.childWindows.push(childWindow);
scope.$on('$destroy', (function(_this) {
return function() {
_this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) {
return child1.scope.$id === child2.scope.$id;
});
return _this.childWindows.length = 0;
};
})(this));
}
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.gObject;
});
};
})(this);
scope.control.getChildWindows = (function(_this) {
return function() {
return _this.childWindows;
};
})(this);
scope.control.getPlurals = scope.control.getChildWindows;
scope.control.showWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.showWindow();
});
};
})(this);
scope.control.hideWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.hideWindow();
});
};
})(this);
}
if ((this.onChildCreation != null) && (childWindow != null)) {
return this.onChildCreation(childWindow);
}
};
return Window;
})(IWindow);
}
]);
}).call(this);
;(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [
'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) {
/*
Windows directive where many windows map to the models property
*/
var Windows;
return Windows = (function(superClass) {
extend(Windows, superClass);
function Windows() {
this.init = bind(this.init, this);
this.link = bind(this.link, this);
Windows.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers'];
this.template = '<span class="angular-google-maps-windows" ng-transclude></span>';
Plural.extend(this);
$log.debug(this);
}
Windows.prototype.link = function(scope, element, attrs, ctrls) {
var mapScope, markerCtrl, markerScope;
mapScope = ctrls[0].getScope();
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
return mapScope.deferred.promise.then((function(_this) {
return function(map) {
var promise, ref;
promise = (markerScope != null ? (ref = markerScope.deferred) != null ? ref.promise : void 0 : void 0) || uiGmapPromise.resolve();
return promise.then(function() {
var pieces, ref1;
pieces = (ref1 = _this.parentModel) != null ? ref1.existingPieces : void 0;
if (pieces) {
return pieces.then(function() {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
});
} else {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
}
});
};
})(this));
};
Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) {
var parentModel;
parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return parentModel.plurals.map(function(child) {
return child.gObject;
});
};
})(this);
return scope.control.getChildWindows = (function(_this) {
return function() {
return parentModel.plurals;
};
})(this);
}
};
return Windows;
})(IWindow);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Nick Baugh - https://github.com/niftylettuce
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [
"uiGmapMap", function(Map) {
return new Map();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [
'$timeout', 'uiGmapMarker', function($timeout, Marker) {
return new Marker($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [
'$timeout', 'uiGmapMarkers', function($timeout, Markers) {
return new Markers($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [
'uiGmapPolygon', function(Polygon) {
return new Polygon();
}
]);
}).call(this);
;
/*
@authors
Julian Popescu - https://github.com/jpopesculian
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [
"uiGmapCircle", function(Circle) {
return Circle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [
"uiGmapPolyline", function(Polyline) {
return new Polyline();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [
'uiGmapPolylines', function(Polylines) {
return new Polylines();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Chentsu Lin - https://github.com/ChenTsuLin
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [
"uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) {
return Rectangle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [
"$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) {
return new Window($timeout, $compile, $http, $templateCache);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [
"$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) {
return new Windows($timeout, $compile, $http, $templateCache, $interpolate);
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [
'$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) {
var Layer;
Layer = (function() {
function Layer() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>';
this.replace = true;
this.scope = {
show: '=show',
type: '=type',
namespace: '=namespace',
options: '=options',
onCreated: '&oncreated'
};
}
Layer.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (scope.onCreated != null) {
return new LayerParentModel(scope, element, attrs, map, scope.onCreated);
} else {
return new LayerParentModel(scope, element, attrs, map);
}
};
})(this));
};
return Layer;
})();
return new Layer();
}
]);
}).call(this);
;
/*
@authors
Adam Kreitals, [email protected]
*/
/*
mapControl directive
This directive is used to create a custom control element on an existing map.
This directive creates a new scope.
{attribute template required} string url of the template to be used for the control
{attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER
{attribute controller optional} string controller to be applied to the template
{attribute index optional} number index for controlling the order of similarly positioned mapControl elements
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [
"uiGmapControl", function(Control) {
return new Control();
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [
'uiGmapDragZoom', function(DragZoom) {
return DragZoom;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [
"uiGmapDrawingManager", function(DrawingManager) {
return DrawingManager;
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
* Brunt of the work is in DrawFreeHandChildModel
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [
'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) {
return new FreeDrawPolygons();
}
]);
}).call(this);
;
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [
"$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) {
var MapType;
MapType = (function() {
function MapType() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = "EMA";
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>';
this.replace = true;
this.scope = {
show: "=show",
options: '=options',
refresh: '=refresh',
id: '@'
};
}
MapType.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new MapTypeParentModel(scope, element, attrs, map);
};
})(this));
};
return MapType;
})();
return new MapType();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [
'uiGmapPolygons', function(Polygons) {
return new Polygons();
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
*/
/*
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
*/
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [
'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) {
var SearchBox;
SearchBox = (function() {
SearchBox.prototype.require = 'ngModel';
function SearchBox() {
this.link = bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>';
this.replace = true;
this.scope = {
template: '=template',
events: '=events',
position: '=?position',
options: '=?options',
parentdiv: '=?parentdiv',
ngModel: "=?"
};
}
SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
if (angular.isUndefined(scope.events)) {
_this.$log.error('searchBox: the events property is required');
return;
}
return mapCtrl.getScope().deferred.promise.then(function(map) {
var ctrlPosition;
ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT';
if (!maps.ControlPosition[ctrlPosition]) {
_this.$log.error('searchBox: invalid position property');
return;
}
return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope));
});
});
};
})(this));
};
return SearchBox;
})();
return new SearchBox();
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [
'$animate', 'uiGmapLogger', function($animate, $log) {
return {
scope: {
'uiGmapShow': '=',
'uiGmapAfterShow': '&',
'uiGmapAfterHide': '&'
},
link: function(scope, element) {
var angular_post_1_3_handle, angular_pre_1_3_handle, handle;
angular_post_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide').then(function() {
return cb();
});
};
angular_pre_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide', cb);
};
handle = function(animateAction, cb) {
if (angular.version.major > 1) {
return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\"");
}
if (angular.version.major === 1 && angular.version.minor < 3) {
return angular_pre_1_3_handle(animateAction, cb);
}
return angular_post_1_3_handle(animateAction, cb);
};
return scope.$watch('uiGmapShow', function(show) {
if (show) {
handle('removeClass', scope.uiGmapAfterShow);
}
if (!show) {
return handle('addClass', scope.uiGmapAfterHide);
}
});
}
};
}
]);
}).call(this);
;angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapuuid', function() {
//BEGIN REPLACE
/*
Version: core-1.0
The MIT License: Copyright (c) 2012 LiosK.
*/
function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c};
//END REPLACE
return UUID;
});
;// wrap the utility libraries needed in ./lib
// http://google-maps-utility-library-v3.googlecode.com/svn/
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapGoogleMapsUtilV3', function () {
return {
init: _.once(function () {
//BEGIN REPLACE
/**
* @name InfoBox
* @version 1.1.13 [March 19, 2014]
* @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)
* @copyright Copyright 2010 Gary Little [gary at luxcentral.com]
* @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class.
* <p>
* An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several
* additional properties for advanced styling. An InfoBox can also be used as a map label.
* <p>
* An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>.
*/
/*!
*
* 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.
*/
/*jslint browser:true */
/*global google */
/**
* @name InfoBoxOptions
* @class This class represents the optional parameter passed to the {@link InfoBox} constructor.
* @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).
* @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>.
* @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.
* @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox
* (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>)
* to the map pixel corresponding to <tt>position</tt>.
* @property {LatLng} position The geographic location at which to display the InfoBox.
* @property {number} zIndex The CSS z-index style value for the InfoBox.
* Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property.
* @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container.
* @property {Object} [boxStyle] An object literal whose properties define specific CSS
* style values to be applied to the InfoBox. Style values defined here override those that may
* be defined in the <code>boxClass</code> style sheet. If this property is changed after the
* InfoBox has been created, all previously set styles (except those defined in the style sheet)
* are removed from the InfoBox before the new style values are applied.
* @property {string} closeBoxMargin The CSS margin style value for the close box.
* The default is "2px" (a 2-pixel margin on all sides).
* @property {string} closeBoxURL The URL of the image representing the close box.
* Note: The default is the URL for Google's standard close box.
* Set this property to "" if no close box is required.
* @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the
* map edge after an auto-pan.
* @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>.
* [Deprecated in favor of the <tt>visible</tt> property.]
* @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>.
* @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code>
* location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned).
* @property {string} pane The pane where the InfoBox is to appear (default is "floatPane").
* Set the pane to "mapPane" if the InfoBox is being used as a map label.
* Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object.
* @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,
* mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox
* (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set
* this property to <tt>true</tt> if the InfoBox is being used as a map label.
*/
/**
* Creates an InfoBox with the options specified in {@link InfoBoxOptions}.
* Call <tt>InfoBox.open</tt> to add the box to the map.
* @constructor
* @param {InfoBoxOptions} [opt_opts]
*/
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
//
this.content_ = opt_opts.content || "";
this.disableAutoPan_ = opt_opts.disableAutoPan || false;
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
//
this.boxClass_ = opt_opts.boxClass || "infoBox";
this.boxStyle_ = opt_opts.boxStyle || {};
this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
if (opt_opts.closeBoxURL === "") {
this.closeBoxURL_ = "";
}
this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
if (typeof opt_opts.visible === "undefined") {
if (typeof opt_opts.isHidden === "undefined") {
opt_opts.visible = true;
} else {
opt_opts.visible = !opt_opts.isHidden;
}
}
this.isHidden_ = !opt_opts.visible;
this.alignBottom_ = opt_opts.alignBottom || false;
this.pane_ = opt_opts.pane || "floatPane";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.moveListener_ = null;
this.contextListener_ = null;
this.eventListeners_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();
/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function () {
var i;
var events;
var bw;
var me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
//
var cancelHandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
// This handler ignores the current event in the InfoBox and conditionally prevents
// the event from being passed on to the map. It is used for the contextmenu event.
//
var ignoreHandler = function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
if (!me.enableEventPropagation_) {
cancelHandler(e);
}
};
if (!this.div_) {
this.div_ = document.createElement("div");
this.setBoxStyle_();
if (typeof this.content_.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(this.content_);
}
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) {
this.fixedWidthSet_ = true;
} else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.div_.style.overflow = "auto";
this.fixedWidthSet_ = true;
} else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
this.panBox_(this.disableAutoPan_);
if (!this.enableEventPropagation_) {
this.eventListeners_ = [];
// Cancel event propagation.
//
// Note: mousemove not included (to resolve Issue 152)
events = ["mousedown", "mouseover", "mouseout", "mouseup",
"click", "dblclick", "touchstart", "touchend", "touchmove"];
for (i = 0; i < events.length; i++) {
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));
}
// Workaround for Google bug that causes the cursor to change to a pointer
// when the mouse moves over a marker underneath InfoBox.
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) {
this.style.cursor = "default";
}));
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
/**
* This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
* @name InfoBox#domready
* @event
*/
google.maps.event.trigger(this, "domready");
}
};
/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function () {
var img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right"; // Do this because Opera chokes on style='float: right;'
img += " style='";
img += " position: relative;"; // Required by MSIE
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
/**
* Adds the click handler to the InfoBox close box.
* @private
*/
InfoBox.prototype.addClickHandler_ = function () {
var closeBox;
if (this.closeBoxURL_ !== "") {
closeBox = this.div_.firstChild;
this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_());
} else {
this.closeListener_ = null;
}
};
/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function () {
var me = this;
return function (e) {
// 1.0.3 fix: Always prevent propagation of a close box click to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
/**
* This event is fired when the InfoBox's close box is clicked.
* @name InfoBox#closeclick
* @event
*/
google.maps.event.trigger(me, "closeclick");
me.close();
};
};
/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function (disablePan) {
var map;
var bounds;
var xOffset = 0, yOffset = 0;
if (!disablePan) {
map = this.getMap();
if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama
if (!map.getBounds().contains(this.position_)) {
// Marker not in visible area of map, so set center
// of map to the marker position first.
map.setCenter(this.position_);
}
bounds = map.getBounds();
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var iwWidth = this.div_.offsetWidth;
var iwHeight = this.div_.offsetHeight;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);
if (pixPosition.x < (-iwOffsetX + padX)) {
xOffset = pixPosition.x + iwOffsetX - padX;
} else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
}
if (this.alignBottom_) {
if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
} else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
}
} else {
if (pixPosition.y < (-iwOffsetY + padY)) {
yOffset = pixPosition.y + iwOffsetY - padY;
} else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
}
}
if (!(xOffset === 0 && yOffset === 0)) {
// Move the map to the shifted center.
//
var c = map.getCenter();
map.panBy(xOffset, yOffset);
}
}
}
};
/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function () {
var i, boxStyle;
if (this.div_) {
// Apply style values from the style sheet defined in the boxClass parameter:
this.div_.className = this.boxClass_;
// Clear existing inline style values:
this.div_.style.cssText = "";
// Apply style values defined in the boxStyle parameter:
boxStyle = this.boxStyle_;
for (i in boxStyle) {
if (boxStyle.hasOwnProperty(i)) {
this.div_.style[i] = boxStyle[i];
}
}
// Fix for iOS disappearing InfoBox problem.
// See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad
this.div_.style.WebkitTransform = "translateZ(0)";
// Fix up opacity style for benefit of MSIE:
//
if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {
// See http://www.quirksmode.org/css/opacity.html
this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\"";
this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
}
// Apply required styles:
//
this.div_.style.position = "absolute";
this.div_.style.visibility = 'hidden';
if (this.zIndex_ !== null) {
this.div_.style.zIndex = this.zIndex_;
}
}
};
/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function () {
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";
if (this.alignBottom_) {
this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
} else {
this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
}
if (this.isHidden_) {
this.div_.style.visibility = "hidden";
} else {
this.div_.style.visibility = "visible";
}
};
/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
* <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
* properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
* is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function (opt_opts) {
if (typeof opt_opts.boxClass !== "undefined") { // Must be first
this.boxClass_ = opt_opts.boxClass;
this.setBoxStyle_();
}
if (typeof opt_opts.boxStyle !== "undefined") { // Must be second
this.boxStyle_ = opt_opts.boxStyle;
this.setBoxStyle_();
}
if (typeof opt_opts.content !== "undefined") {
this.setContent(opt_opts.content);
}
if (typeof opt_opts.disableAutoPan !== "undefined") {
this.disableAutoPan_ = opt_opts.disableAutoPan;
}
if (typeof opt_opts.maxWidth !== "undefined") {
this.maxWidth_ = opt_opts.maxWidth;
}
if (typeof opt_opts.pixelOffset !== "undefined") {
this.pixelOffset_ = opt_opts.pixelOffset;
}
if (typeof opt_opts.alignBottom !== "undefined") {
this.alignBottom_ = opt_opts.alignBottom;
}
if (typeof opt_opts.position !== "undefined") {
this.setPosition(opt_opts.position);
}
if (typeof opt_opts.zIndex !== "undefined") {
this.setZIndex(opt_opts.zIndex);
}
if (typeof opt_opts.closeBoxMargin !== "undefined") {
this.closeBoxMargin_ = opt_opts.closeBoxMargin;
}
if (typeof opt_opts.closeBoxURL !== "undefined") {
this.closeBoxURL_ = opt_opts.closeBoxURL;
}
if (typeof opt_opts.infoBoxClearance !== "undefined") {
this.infoBoxClearance_ = opt_opts.infoBoxClearance;
}
if (typeof opt_opts.isHidden !== "undefined") {
this.isHidden_ = opt_opts.isHidden;
}
if (typeof opt_opts.visible !== "undefined") {
this.isHidden_ = !opt_opts.visible;
}
if (typeof opt_opts.enableEventPropagation !== "undefined") {
this.enableEventPropagation_ = opt_opts.enableEventPropagation;
}
if (this.div_) {
this.draw();
}
};
/**
* Sets the content of the InfoBox.
* The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function (content) {
this.content_ = content;
if (this.div_) {
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
// Odd code required to make things work with MSIE.
//
if (!this.fixedWidthSet_) {
this.div_.style.width = "";
}
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
// Perverse code required to make things work with MSIE.
// (Ensures the close box does, in fact, float to the right.)
//
if (!this.fixedWidthSet_) {
this.div_.style.width = this.div_.offsetWidth + "px";
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
}
this.addClickHandler_();
}
/**
* This event is fired when the content of the InfoBox changes.
* @name InfoBox#content_changed
* @event
*/
google.maps.event.trigger(this, "content_changed");
};
/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) {
this.draw();
}
/**
* This event is fired when the position of the InfoBox changes.
* @name InfoBox#position_changed
* @event
*/
google.maps.event.trigger(this, "position_changed");
};
/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function (index) {
this.zIndex_ = index;
if (this.div_) {
this.div_.style.zIndex = index;
}
/**
* This event is fired when the zIndex of the InfoBox changes.
* @name InfoBox#zindex_changed
* @event
*/
google.maps.event.trigger(this, "zindex_changed");
};
/**
* Sets the visibility of the InfoBox.
* @param {boolean} isVisible
*/
InfoBox.prototype.setVisible = function (isVisible) {
this.isHidden_ = !isVisible;
if (this.div_) {
this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible");
}
};
/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function () {
return this.content_;
};
/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function () {
return this.position_;
};
/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function () {
return this.zIndex_;
};
/**
* Returns a flag indicating whether the InfoBox is visible.
* @returns {boolean}
*/
InfoBox.prototype.getVisible = function () {
var isVisible;
if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) {
isVisible = false;
} else {
isVisible = !this.isHidden_;
}
return isVisible;
};
/**
* Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.show = function () {
this.isHidden_ = false;
if (this.div_) {
this.div_.style.visibility = "visible";
}
};
/**
* Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.hide = function () {
this.isHidden_ = true;
if (this.div_) {
this.div_.style.visibility = "hidden";
}
};
/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
* (usually a <tt>google.maps.Marker</tt>) is specified, the position
* of the InfoBox is set to the position of the <tt>anchor</tt>. If the
* anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function (map, anchor) {
var me = this;
if (anchor) {
this.position_ = anchor.getPosition();
this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () {
me.setPosition(this.getPosition());
});
}
this.setMap(map);
if (this.div_) {
this.panBox_();
}
};
/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function () {
var i;
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.eventListeners_) {
for (i = 0; i < this.eventListeners_.length; i++) {
google.maps.event.removeListener(this.eventListeners_[i]);
}
this.eventListeners_ = null;
}
if (this.moveListener_) {
google.maps.event.removeListener(this.moveListener_);
this.moveListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
/**
* @name KeyDragZoom for V3
* @version 2.0.9 [December 17, 2012] NOT YET RELEASED
* @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com]
* @fileoverview This library adds a drag zoom capability to a V3 Google map.
* When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code>
* while dragging a box around an area of interest will zoom the map in to that area when
* the mouse button is released. Optionally, a visual control can also be supplied for turning
* a drag zoom operation on and off.
* Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code>
* <p>
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh.
* <p>
* Note that if the map's container has a border around it, the border widths must be specified
* in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation.
* <p>NL: 2009-05-28: initial port to core API V3.
* <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove).
* <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position.
* <br>GL: 2010-06-15: added a visual control option.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
/*jslint browser:true */
/*global window,google */
/* Utility functions use "var funName=function()" syntax to allow use of the */
/* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */
/**
* Converts "thin", "medium", and "thick" to pixel widths
* in an MSIE environment. Not called for other browsers
* because getComputedStyle() returns pixel widths automatically.
* @param {string} widthValue The value of the border width parameter.
*/
var toPixels = function (widthValue) {
var px;
switch (widthValue) {
case "thin":
px = "2px";
break;
case "medium":
px = "4px";
break;
case "thick":
px = "6px";
break;
default:
px = widthValue;
}
return px;
};
/**
* Get the widths of the borders of an HTML element.
*
* @param {Node} h The HTML element.
* @return {Object} The width object {top, bottom left, right}.
*/
var getBorderWidths = function (h) {
var computedStyle;
var bw = {};
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
return bw;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (h.currentStyle) {
// The current styles may not be in pixel units so try to convert (bad!)
bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0;
bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0;
bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0;
bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0;
return bw;
}
}
// Shouldn't get this far for any modern browser
bw.top = parseInt(h.style["border-top-width"], 10) || 0;
bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0;
bw.left = parseInt(h.style["border-left-width"], 10) || 0;
bw.right = parseInt(h.style["border-right-width"], 10) || 0;
return bw;
};
// Page scroll values for use by getMousePosition. To prevent flickering on MSIE
// they are calculated only when the document actually scrolls, not every time the
// mouse moves (as they would be if they were calculated inside getMousePosition).
var scroll = {
x: 0,
y: 0
};
var getScrollValue = function (e) {
scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft);
scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop);
};
getScrollValue();
/**
* Get the position of the mouse relative to the document.
* @param {Event} e The mouse event.
* @return {Object} The position object {left, top}.
*/
var getMousePosition = function (e) {
var posX = 0, posY = 0;
e = e || window.event;
if (typeof e.pageX !== "undefined") {
posX = e.pageX;
posY = e.pageY;
} else if (typeof e.clientX !== "undefined") { // MSIE
posX = e.clientX + scroll.x;
posY = e.clientY + scroll.y;
}
return {
left: posX,
top: posY
};
};
/**
* Get the position of an HTML element relative to the document.
* @param {Node} h The HTML element.
* @return {Object} The position object {left, top}.
*/
var getElementPosition = function (h) {
var posX = h.offsetLeft;
var posY = h.offsetTop;
var parent = h.offsetParent;
// Add offsets for all ancestors in the hierarchy
while (parent !== null) {
// Adjust for scrolling elements which may affect the map position.
//
// See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific
//
// "...make sure that every element [on a Web page] with an overflow
// of anything other than visible also has a position style set to
// something other than the default static..."
if (parent !== document.body && parent !== document.documentElement) {
posX -= parent.scrollLeft;
posY -= parent.scrollTop;
}
// See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5
// Example: http://notebook.kulchenko.com/maps/gridmove
var m = parent;
// This is the "normal" way to get offset information:
var moffx = m.offsetLeft;
var moffy = m.offsetTop;
// This covers those cases where a transform is used:
if (!moffx && !moffy && window.getComputedStyle) {
var matrix = document.defaultView.getComputedStyle(m, null).MozTransform ||
document.defaultView.getComputedStyle(m, null).WebkitTransform;
if (matrix) {
if (typeof matrix === "string") {
var parms = matrix.split(",");
moffx += parseInt(parms[4], 10) || 0;
moffy += parseInt(parms[5], 10) || 0;
}
}
}
posX += moffx;
posY += moffy;
parent = parent.offsetParent;
}
return {
left: posX,
top: posY
};
};
/**
* Set the properties of an object to those from another object.
* @param {Object} obj The target object.
* @param {Object} vals The source object.
*/
var setVals = function (obj, vals) {
if (obj && vals) {
for (var x in vals) {
if (vals.hasOwnProperty(x)) {
obj[x] = vals[x];
}
}
}
return obj;
};
/**
* Set the opacity. If op is not passed in, this function just performs an MSIE fix.
* @param {Node} h The HTML element.
* @param {number} op The opacity value (0-1).
*/
var setOpacity = function (h, op) {
if (typeof op !== "undefined") {
h.style.opacity = op;
}
if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") {
h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")";
}
};
/**
* @name KeyDragZoomOptions
* @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>.
* @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>.
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh. Also note that the
* <code>alt</code> hot key refers to the Option key on a Macintosh.
* @property {Object} [boxStyle={border: "4px solid #736AFF"}]
* An object literal defining the CSS styles of the zoom box.
* Border widths must be specified in pixel units (or as thin, medium, or thick).
* @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}]
* An object literal defining the CSS styles of the veil pane which covers the map when a drag
* zoom is activated. The previous name for this property was <code>paneStyle</code> but the use
* of this name is now deprecated.
* @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is
* selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area
* selection tool.
* @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used.
* @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual
* control. To prevent the visual control from being printed, set this property to the name of
* a class, defined inside a <code>@media print</code> rule, which sets the CSS
* <code>display</code> style to <code>none</code>.
* @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP]
* The position of the visual control.
* @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values
* provided by this property are the offsets (in pixels) from the location at which the control
* would normally be drawn to the desired drawing location.
* @property {number} [visualPositionIndex=null] The index of the visual control.
* The index is for controlling the placement of the control relative to other controls at the
* position given by <code>visualPosition</code>; controls with a lower index are placed first.
* Use a negative value to place the control <i>before</i> any default controls. No index is
* generally required.
* @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"]
* The URL of the sprite image used for showing the visual control in the on, off, and hot
* (i.e., when the mouse is over the control) states. The three images within the sprite must
* be the same size and arranged in on-hot-off order in a single row with no spaces between images.
* @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by
* this property are the size (in pixels) of each of the images within <code>visualSprite</code>.
* @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}]
* An object literal defining the help tips that appear when
* the mouse moves over the visual control. The <code>off</code> property is the tip to be shown
* when the control is off and the <code>on</code> property is the tip to be shown when the
* control is on.
*/
/**
* @name DragZoom
* @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key
* or by turning on the visual control.
* This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly.
* Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
function DragZoom(map, opt_zoomOpts) {
var me = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
}
/**
* Initialize the tool.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
DragZoom.prototype.init_ = function (map, opt_zoomOpts) {
var i;
var me = this;
this.map_ = map;
opt_zoomOpts = opt_zoomOpts || {};
this.key_ = opt_zoomOpts.key || "shift";
this.key_ = this.key_.toLowerCase();
this.borderWidths_ = getBorderWidths(this.map_.getDiv());
this.veilDiv_ = [];
for (i = 0; i < 4; i++) {
this.veilDiv_[i] = document.createElement("div");
// Prevents selection of other elements on the webpage
// when a drag zoom operation is in progress:
this.veilDiv_[i].onselectstart = function () {
return false;
};
// Apply default style values for the veil:
setVals(this.veilDiv_[i].style, {
backgroundColor: "gray",
opacity: 0.25,
cursor: "crosshair"
});
// Apply style values specified in veilStyle parameter:
setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle"
setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle"
// Apply mandatory style values:
setVals(this.veilDiv_[i].style, {
position: "absolute",
overflow: "hidden",
display: "none"
});
// Workaround for Firefox Shift-Click problem:
if (this.key_ === "shift") {
this.veilDiv_[i].style.MozUserSelect = "none";
}
setOpacity(this.veilDiv_[i]);
// An IE fix: If the background is transparent it cannot capture mousedown
// events, so if it is, change the background to white with 0 opacity.
if (this.veilDiv_[i].style.backgroundColor === "transparent") {
this.veilDiv_[i].style.backgroundColor = "white";
setOpacity(this.veilDiv_[i], 0);
}
this.map_.getDiv().appendChild(this.veilDiv_[i]);
}
this.noZoom_ = opt_zoomOpts.noZoom || false;
this.visualEnabled_ = opt_zoomOpts.visualEnabled || false;
this.visualClass_ = opt_zoomOpts.visualClass || "";
this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP;
this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0);
this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null;
this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png";
this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20);
this.visualTips_ = opt_zoomOpts.visualTips || {};
this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode";
this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode";
this.boxDiv_ = document.createElement("div");
// Apply default style values for the zoom box:
setVals(this.boxDiv_.style, {
border: "4px solid #736AFF"
});
// Apply style values specified in boxStyle parameter:
setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle);
// Apply mandatory style values:
setVals(this.boxDiv_.style, {
position: "absolute",
display: "none"
});
setOpacity(this.boxDiv_);
this.map_.getDiv().appendChild(this.boxDiv_);
this.boxBorderWidths_ = getBorderWidths(this.boxDiv_);
this.listeners_ = [
google.maps.event.addDomListener(document, "keydown", function (e) {
me.onKeyDown_(e);
}),
google.maps.event.addDomListener(document, "keyup", function (e) {
me.onKeyUp_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(document, "mousedown", function (e) {
me.onMouseDownDocument_(e);
}),
google.maps.event.addDomListener(document, "mousemove", function (e) {
me.onMouseMove_(e);
}),
google.maps.event.addDomListener(document, "mouseup", function (e) {
me.onMouseUp_(e);
}),
google.maps.event.addDomListener(window, "scroll", getScrollValue)
];
this.hotKeyDown_ = false;
this.mouseDown_ = false;
this.dragging_ = false;
this.startPt_ = null;
this.endPt_ = null;
this.mapWidth_ = null;
this.mapHeight_ = null;
this.mousePosn_ = null;
this.mapPosn_ = null;
if (this.visualEnabled_) {
this.buttonDiv_ = this.initControl_(this.visualPositionOffset_);
if (this.visualPositionIndex_ !== null) {
this.buttonDiv_.index = this.visualPositionIndex_;
}
this.map_.controls[this.visualPosition_].push(this.buttonDiv_);
this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1;
}
};
/**
* Initializes the visual control and returns its DOM element.
* @param {Size} offset The offset of the control from its normal position.
* @return {Node} The DOM element containing the visual control.
*/
DragZoom.prototype.initControl_ = function (offset) {
var control;
var image;
var me = this;
control = document.createElement("div");
control.className = this.visualClass_;
control.style.position = "relative";
control.style.overflow = "hidden";
control.style.height = this.visualSize_.height + "px";
control.style.width = this.visualSize_.width + "px";
control.title = this.visualTips_.off;
image = document.createElement("img");
image.src = this.visualSprite_;
image.style.position = "absolute";
image.style.left = -(this.visualSize_.width * 2) + "px";
image.style.top = 0 + "px";
control.appendChild(image);
control.onclick = function (e) {
me.hotKeyDown_ = !me.hotKeyDown_;
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
me.activatedByControl_ = true;
google.maps.event.trigger(me, "activate");
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
google.maps.event.trigger(me, "deactivate");
}
me.onMouseMove_(e); // Updates the veil
};
control.onmouseover = function () {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px";
};
control.onmouseout = function () {
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
}
};
control.ondragstart = function () {
return false;
};
setVals(control.style, {
cursor: "pointer",
marginTop: offset.height + "px",
marginLeft: offset.width + "px"
});
return control;
};
/**
* Returns <code>true</code> if the hot key is being pressed when an event occurs.
* @param {Event} e The keyboard event.
* @return {boolean} Flag indicating whether the hot key is down.
*/
DragZoom.prototype.isHotKeyDown_ = function (e) {
var isHot;
e = e || window.event;
isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl");
if (!isHot) {
// Need to look at keyCode for Opera because it
// doesn't set the shiftKey, altKey, ctrlKey properties
// unless a non-modifier event is being reported.
//
// See http://cross-browser.com/x/examples/shift_mode.php
// Also see http://unixpapa.com/js/key.html
switch (e.keyCode) {
case 16:
if (this.key_ === "shift") {
isHot = true;
}
break;
case 17:
if (this.key_ === "ctrl") {
isHot = true;
}
break;
case 18:
if (this.key_ === "alt") {
isHot = true;
}
break;
}
}
return isHot;
};
/**
* Returns <code>true</code> if the mouse is on top of the map div.
* The position is captured in onMouseMove_.
* @return {boolean}
*/
DragZoom.prototype.isMouseOnMap_ = function () {
var mousePosn = this.mousePosn_;
if (mousePosn) {
var mapPosn = this.mapPosn_;
var mapDiv = this.map_.getDiv();
return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) &&
mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight);
} else {
// if user never moved mouse
return false;
}
};
/**
* Show the veil if the hot key is down and the mouse is over the map,
* otherwise hide the veil.
*/
DragZoom.prototype.setVeilVisibility_ = function () {
var i;
if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) {
var mapDiv = this.map_.getDiv();
this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right);
this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom);
if (this.activatedByControl_) { // Veil covers entire map (except control)
var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width;
var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height;
var width = this.visualSize_.width;
var height = this.visualSize_.height;
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
} else {
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.width = this.mapWidth_ + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
for (i = 1; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.width = "0px";
this.veilDiv_[i].style.height = "0px";
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
}
} else {
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
}
};
/**
* Handle key down. Show the veil if the hot key has been pressed.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyDown_ = function (e) {
if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.hotKeyDown_ = true;
this.activatedByControl_ = false;
this.setVeilVisibility_();
/**
* This event is fired when the hot key is pressed.
* @name DragZoom#activate
* @event
*/
google.maps.event.trigger(this, "activate");
}
};
/**
* Get the <code>google.maps.Point</code> of the mouse position.
* @param {Event} e The mouse event.
* @return {Point} The mouse position.
*/
DragZoom.prototype.getMousePoint_ = function (e) {
var mousePosn = getMousePosition(e);
var p = new google.maps.Point();
p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left;
p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top;
p.x = Math.min(p.x, this.mapWidth_);
p.y = Math.min(p.y, this.mapHeight_);
p.x = Math.max(p.x, 0);
p.y = Math.max(p.y, 0);
return p;
};
/**
* Handle mouse down.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDown_ = function (e) {
if (this.map_ && this.hotKeyDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.dragging_ = true;
this.startPt_ = this.endPt_ = this.getMousePoint_(e);
this.boxDiv_.style.width = this.boxDiv_.style.height = "0px";
var prj = this.prjov_.getProjection();
var latlng = prj.fromContainerPixelToLatLng(this.startPt_);
/**
* This event is fired when the drag operation begins.
* The parameter passed is the geographic position of the starting point.
* @name DragZoom#dragstart
* @param {LatLng} latlng The geographic position of the starting point.
* @event
*/
google.maps.event.trigger(this, "dragstart", latlng);
}
};
/**
* Handle mouse down at the document level.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDownDocument_ = function (e) {
this.mouseDown_ = true;
};
/**
* Handle mouse move.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseMove_ = function (e) {
this.mousePosn_ = getMousePosition(e);
if (this.dragging_) {
this.endPt_ = this.getMousePoint_(e);
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// For benefit of MSIE 7/8 ensure following values are not negative:
var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right));
var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom));
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
// Selection rectangle:
this.boxDiv_.style.top = top + "px";
this.boxDiv_.style.left = left + "px";
this.boxDiv_.style.width = boxWidth + "px";
this.boxDiv_.style.height = boxHeight + "px";
this.boxDiv_.style.display = "block";
/**
* This event is fired repeatedly while the user drags a box across the area of interest.
* The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code>
* (for performance reasons), relative to the map container. Also passed is the projection object
* so that the event listener, if necessary, can convert the pixel positions to geographic
* coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>.
* @name DragZoom#drag
* @param {Point} southwestPixel The southwest point of the selection area.
* @param {Point} northeastPixel The northeast point of the selection area.
* @param {MapCanvasProjection} prj The projection object.
* @event
*/
google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection());
} else if (!this.mouseDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.setVeilVisibility_();
}
};
/**
* Handle mouse up.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseUp_ = function (e) {
var z;
var me = this;
this.mouseDown_ = false;
if (this.dragging_) {
if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) {
this.onKeyUp_(e); // Cancel event
return;
}
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// Google Maps API bug: setCenter() doesn't work as expected if the map has a
// border on the left or top. The code here includes a workaround for this problem.
var kGoogleCenteringBug = true;
if (kGoogleCenteringBug) {
left += this.borderWidths_.left;
top += this.borderWidths_.top;
}
var prj = this.prjov_.getProjection();
var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
if (this.noZoom_) {
this.boxDiv_.style.display = "none";
} else {
// Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens.
z = this.map_.getZoom();
this.map_.fitBounds(bnds);
if (this.map_.getZoom() < z) {
this.map_.setZoom(z);
}
// Redraw box after zoom:
var swPt = prj.fromLatLngToContainerPixel(sw);
var nePt = prj.fromLatLngToContainerPixel(ne);
if (kGoogleCenteringBug) {
swPt.x -= this.borderWidths_.left;
swPt.y -= this.borderWidths_.top;
nePt.x -= this.borderWidths_.left;
nePt.y -= this.borderWidths_.top;
}
this.boxDiv_.style.left = swPt.x + "px";
this.boxDiv_.style.top = nePt.y + "px";
this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px";
this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px";
// Hide box asynchronously after 1 second:
setTimeout(function () {
me.boxDiv_.style.display = "none";
}, 1000);
}
this.dragging_ = false;
this.onMouseMove_(e); // Updates the veil
/**
* This event is fired when the drag operation ends.
* The parameter passed is the geographic bounds of the selected area.
* Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends.
* @name DragZoom#dragend
* @param {LatLngBounds} bnds The geographic bounds of the selected area.
* @event
*/
google.maps.event.trigger(this, "dragend", bnds);
// if the hot key isn't down, the drag zoom must have been activated by turning
// on the visual control. In this case, finish up by simulating a key up event.
if (!this.isHotKeyDown_(e)) {
this.onKeyUp_(e);
}
}
};
/**
* Handle key up.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyUp_ = function (e) {
var i;
var left, top, width, height, prj, sw, ne;
var bnds = null;
if (this.map_ && this.hotKeyDown_) {
this.hotKeyDown_ = false;
if (this.dragging_) {
this.boxDiv_.style.display = "none";
this.dragging_ = false;
// Calculate the bounds when drag zoom was cancelled
left = Math.min(this.startPt_.x, this.endPt_.x);
top = Math.min(this.startPt_.y, this.endPt_.y);
width = Math.abs(this.startPt_.x - this.endPt_.x);
height = Math.abs(this.startPt_.y - this.endPt_.y);
prj = this.prjov_.getProjection();
sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
bnds = new google.maps.LatLngBounds(sw, ne);
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
if (this.visualEnabled_) {
this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px";
this.buttonDiv_.title = this.visualTips_.off;
this.buttonDiv_.style.display = "";
}
/**
* This event is fired when the hot key is released.
* The parameter passed is the geographic bounds of the selected area immediately
* before the hot key was released.
* @name DragZoom#deactivate
* @param {LatLngBounds} bnds The geographic bounds of the selected area immediately
* before the hot key was released.
* @event
*/
google.maps.event.trigger(this, "deactivate", bnds);
}
};
/**
* @name google.maps.Map
* @class These are new methods added to the Google Maps JavaScript API V3's
* <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a>
* class.
*/
/**
* Enables drag zoom. The user can zoom to an area of interest by holding down the hot key
* <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning
* on the visual control then dragging a box around the area.
* @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters.
*/
google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) {
this.dragZoom_ = new DragZoom(this, opt_zoomOpts);
};
/**
* Disables drag zoom.
*/
google.maps.Map.prototype.disableKeyDragZoom = function () {
var i;
var d = this.dragZoom_;
if (d) {
for (i = 0; i < d.listeners_.length; ++i) {
google.maps.event.removeListener(d.listeners_[i]);
}
this.getDiv().removeChild(d.boxDiv_);
for (i = 0; i < d.veilDiv_.length; i++) {
this.getDiv().removeChild(d.veilDiv_[i]);
}
if (d.visualEnabled_) {
// Remove the custom control:
this.controls[d.visualPosition_].removeAt(d.controlIndex_);
}
d.prjov_.setMap(null);
this.dragZoom_ = null;
}
};
/**
* Returns <code>true</code> if the drag zoom feature has been enabled.
* @return {boolean}
*/
google.maps.Map.prototype.keyDragZoomEnabled = function () {
return this.dragZoom_ !== null;
};
/**
* Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called.
* With this object you can use <code>google.maps.event.addListener</code> to attach event listeners
* for the "activate", "deactivate", "dragstart", "drag", and "dragend" events.
* @return {DragZoom}
*/
google.maps.Map.prototype.getDragZoomObject = function () {
return this.dragZoom_;
};
})();
/**
* @name MarkerClustererPlus for Google Maps V3
* @version 2.1.1 [November 4, 2013]
* @author Gary Little
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of markers.
* <p>
* This is an enhanced V3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
* <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
* >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
* <p>
* v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
* adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
* and <code>calculator</code> properties as well as support for four more events. It also allows
* greater control over the styling of the text that appears on the cluster marker. The
* documentation has been significantly improved and the overall code has been simplified and
* polished. Very large numbers of markers can now be managed without causing Javascript timeout
* errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
* deprecated. The new name is <code>click</code>, so please change your application code now.
*/
/**
* 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.
*/
/**
* @name ClusterIconStyle
* @class This class represents the object for values in the <code>styles</code> array passed
* to the {@link MarkerClusterer} constructor. The element in this array that is used to
* style the cluster icon is determined by calling the <code>calculator</code> function.
*
* @property {string} url The URL of the cluster icon image file. Required.
* @property {number} height The display height (in pixels) of the cluster icon. Required.
* @property {number} width The display width (in pixels) of the cluster icon. Required.
* @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
* where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
* where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
* increases to the right of center. The default is <code>[0, 0]</code>.
* @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
* spot on the cluster icon that is to be aligned with the cluster position. The format is
* <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
* <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
* anchor position is the center of the cluster icon.
* @property {string} [textColor="black"] The color of the label text shown on the
* cluster icon.
* @property {number} [textSize=11] The size (in pixels) of the label text shown on the
* cluster icon.
* @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
* property for the label text shown on the cluster icon.
* @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
* within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
* (the same format as for the CSS <code>background-position</code> property). You must set
* this property appropriately when the image defined by <code>url</code> represents a sprite
* containing multiple images. Note that the position <i>must</i> be specified in px units.
*/
/**
* @name ClusterIconInfo
* @class This class is an object containing general information about a cluster icon. This is
* the object that a <code>calculator</code> function returns.
*
* @property {string} text The text of the label to be shown on the cluster icon.
* @property {number} index The index plus 1 of the element in the <code>styles</code>
* array to be used to style the cluster icon.
* @property {string} title The tooltip to display when the mouse moves over the cluster icon.
* If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
* value of the <code>title</code> property passed to the MarkerClusterer.
*/
/**
* A cluster icon.
*
* @constructor
* @extends google.maps.OverlayView
* @param {Cluster} cluster The cluster with which the icon is to be associated.
* @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
* to use for various cluster sizes.
* @private
*/
function ClusterIcon(cluster, styles) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.cluster_ = cluster;
this.className_ = cluster.getMarkerClusterer().getClusterClass();
this.styles_ = styles;
this.center_ = null;
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}
/**
* Adds the icon to the DOM.
*/
ClusterIcon.prototype.onAdd = function () {
var cClusterIcon = this;
var cMouseDownInCluster;
var cDraggingMapByCluster;
this.div_ = document.createElement("div");
this.div_.className = this.className_;
if (this.visible_) {
this.show();
}
this.getPanes().overlayMouseTarget.appendChild(this.div_);
// Fix for Issue 157
this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () {
cDraggingMapByCluster = cMouseDownInCluster;
});
google.maps.event.addDomListener(this.div_, "mousedown", function () {
cMouseDownInCluster = true;
cDraggingMapByCluster = false;
});
google.maps.event.addDomListener(this.div_, "click", function (e) {
cMouseDownInCluster = false;
if (!cDraggingMapByCluster) {
var theBounds;
var mz;
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when a cluster marker is clicked.
* @name MarkerClusterer#click
* @param {Cluster} c The cluster that was clicked.
* @event
*/
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// The default click handler follows. Disable it by setting
// the zoomOnClick property to false.
if (mc.getZoomOnClick()) {
// Zoom into the cluster.
mz = mc.getMaxZoom();
theBounds = cClusterIcon.cluster_.getBounds();
mc.getMap().fitBounds(theBounds);
// There is a fix for Issue 170 here:
setTimeout(function () {
mc.getMap().fitBounds(theBounds);
// Don't zoom beyond the max zoom level
if (mz !== null && (mc.getMap().getZoom() > mz)) {
mc.getMap().setZoom(mz + 1);
}
}, 100);
}
// Prevent event propagation to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
});
google.maps.event.addDomListener(this.div_, "mouseover", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves over a cluster marker.
* @name MarkerClusterer#mouseover
* @param {Cluster} c The cluster that the mouse moved over.
* @event
*/
google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
});
google.maps.event.addDomListener(this.div_, "mouseout", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves out of a cluster marker.
* @name MarkerClusterer#mouseout
* @param {Cluster} c The cluster that the mouse moved out of.
* @event
*/
google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
});
};
/**
* Removes the icon from the DOM.
*/
ClusterIcon.prototype.onRemove = function () {
if (this.div_ && this.div_.parentNode) {
this.hide();
google.maps.event.removeListener(this.boundsChangedListener_);
google.maps.event.clearInstanceListeners(this.div_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the icon.
*/
ClusterIcon.prototype.draw = function () {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + "px";
this.div_.style.left = pos.x + "px";
}
};
/**
* Hides the icon.
*/
ClusterIcon.prototype.hide = function () {
if (this.div_) {
this.div_.style.display = "none";
}
this.visible_ = false;
};
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
/**
* Sets the icon styles to the appropriate element in the styles array.
*
* @param {ClusterIconInfo} sums The icon label text and styles index.
*/
ClusterIcon.prototype.useStyle = function (sums) {
this.sums_ = sums;
var index = Math.max(0, sums.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style.url;
this.height_ = style.height;
this.width_ = style.width;
this.anchorText_ = style.anchorText || [0, 0];
this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
this.textColor_ = style.textColor || "black";
this.textSize_ = style.textSize || 11;
this.textDecoration_ = style.textDecoration || "none";
this.fontWeight_ = style.fontWeight || "bold";
this.fontStyle_ = style.fontStyle || "normal";
this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
this.backgroundPosition_ = style.backgroundPosition || "0 0";
};
/**
* Sets the position at which to center the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function (center) {
this.center_ = center;
};
/**
* Creates the cssText style parameter based on the position of the icon.
*
* @param {google.maps.Point} pos The position of the icon.
* @return {string} The CSS style text.
*/
ClusterIcon.prototype.createCss = function (pos) {
var style = [];
style.push("cursor: pointer;");
style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
return style.join("");
};
/**
* Returns the position at which to place the DIV depending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
*/
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
pos.x -= this.anchorIcon_[1];
pos.y -= this.anchorIcon_[0];
pos.x = parseInt(pos.x, 10);
pos.y = parseInt(pos.y, 10);
return pos;
};
/**
* Creates a single cluster that manages a group of proximate markers.
* Used internally, do not call this constructor directly.
* @constructor
* @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
* cluster is associated.
*/
function Cluster(mc) {
this.markerClusterer_ = mc;
this.map_ = mc.getMap();
this.gridSize_ = mc.getGridSize();
this.minClusterSize_ = mc.getMinimumClusterSize();
this.averageCenter_ = mc.getAverageCenter();
this.markers_ = [];
this.center_ = null;
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}
/**
* Returns the number of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {number} The number of markers in the cluster.
*/
Cluster.prototype.getSize = function () {
return this.markers_.length;
};
/**
* Returns the array of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {Array} The array of markers in the cluster.
*/
Cluster.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the center of the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {google.maps.LatLng} The center of the cluster.
*/
Cluster.prototype.getCenter = function () {
return this.center_;
};
/**
* Returns the map with which the cluster is associated.
*
* @return {google.maps.Map} The map.
* @ignore
*/
Cluster.prototype.getMap = function () {
return this.map_;
};
/**
* Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
*
* @return {MarkerClusterer} The associated marker clusterer.
* @ignore
*/
Cluster.prototype.getMarkerClusterer = function () {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
Cluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
Cluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = [];
delete this.markers_;
};
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
Cluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
for (i = 0; i < mCount; i++) {
this.markers_[i].setMap(null);
}
} else {
marker.setMap(null);
}
this.updateIcon_();
return true;
};
/**
* Determines if a marker lies within the cluster's bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
* @ignore
*/
Cluster.prototype.isMarkerInClusterBounds = function (marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Calculates the extended bounds of the cluster with the grid.
*/
Cluster.prototype.calculateBounds_ = function () {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Updates the cluster icon.
*/
Cluster.prototype.updateIcon_ = function () {
var mCount = this.markers_.length;
var mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
this.clusterIcon_.hide();
return;
}
if (mCount < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.useStyle(sums);
this.clusterIcon_.show();
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
var i;
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) !== -1;
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
return true;
}
}
}
return false;
};
/**
* @name MarkerClustererOptions
* @class This class represents the optional parameter passed to
* the {@link MarkerClusterer} constructor.
* @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
* @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
* <code>null</code> if clustering is to be enabled at all zoom levels.
* @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
* clicked. You may want to set this to <code>false</code> if you have installed a handler
* for the <code>click</code> event and it deals with zooming on its own.
* @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
* the average position of all markers in the cluster. If set to <code>false</code>, the
* cluster marker is positioned at the location of the first marker added to the cluster.
* @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
* before the markers are hidden and a cluster marker appears.
* @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
* may want to set this to <code>true</code> to ensure that hidden markers are not included
* in the marker count that appears on a cluster marker (this count is the value of the
* <code>text</code> property of the result returned by the default <code>calculator</code>).
* If set to <code>true</code> and you change the visibility of a marker being clustered, be
* sure to also call <code>MarkerClusterer.repaint()</code>.
* @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
* marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
* different tooltip for each cluster marker.)
* @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
* the text to be displayed on a cluster marker and the index indicating which style to use
* for the cluster marker. The input parameters for the function are (1) the array of markers
* represented by a cluster marker and (2) the number of cluster icon styles. It returns a
* {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
* <code>text</code> property which is the number of markers in the cluster and an
* <code>index</code> property which is one higher than the lowest integer such that
* <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
* array, whichever is less. The <code>styles</code> array element used has an index of
* <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
* <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
* for a cluster icon representing 125 markers so the element used in the <code>styles</code>
* array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
* property that contains the text of the tooltip to be used for the cluster marker. If
* <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
* property for the MarkerClusterer.
* @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
* for the cluster markers. Use this class to define CSS styles that are not set up by the code
* that processes the <code>styles</code> array.
* @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
* of the cluster markers to be used. The element to be used to style a given cluster marker
* is determined by the function defined by the <code>calculator</code> property.
* The default is an array of {@link ClusterIconStyle} elements whose properties are derived
* from the values for <code>imagePath</code>, <code>imageExtension</code>, and
* <code>imageSizes</code>.
* @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
* have sizes that are some multiple (typically double) of their actual display size. Icons such
* as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
* Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
* @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
* number of markers to be processed in a single batch when using a browser other than
* Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
* @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
* being used, markers are processed in several batches with a small delay inserted between
* each batch in an attempt to avoid Javascript timeout errors. Set this property to the
* number of markers to be processed in a single batch; select as high a number as you can
* without causing a timeout error in the browser. This number might need to be as low as 100
* if 15,000 markers are being managed, for example.
* @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
* The full URL of the root name of the group of image files to use for cluster icons.
* The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
* where n is the image file number (1, 2, etc.).
* @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
* The extension name for the cluster icon image files (e.g., <code>"png"</code> or
* <code>"jpg"</code>).
* @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
* An array of numbers containing the widths of the group of
* <code>imagePath</code>n.<code>imageExtension</code> image files.
* (The images are assumed to be square.)
*/
/**
* Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
* @constructor
* @extends google.maps.OverlayView
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
* @param {MarkerClustererOptions} [opt_options] The optional parameters.
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
opt_markers = opt_markers || [];
opt_options = opt_options || {};
this.markers_ = [];
this.clusters_ = [];
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
this.gridSize_ = opt_options.gridSize || 60;
this.minClusterSize_ = opt_options.minimumClusterSize || 2;
this.maxZoom_ = opt_options.maxZoom || null;
this.styles_ = opt_options.styles || [];
this.title_ = opt_options.title || "";
this.zoomOnClick_ = true;
if (opt_options.zoomOnClick !== undefined) {
this.zoomOnClick_ = opt_options.zoomOnClick;
}
this.averageCenter_ = false;
if (opt_options.averageCenter !== undefined) {
this.averageCenter_ = opt_options.averageCenter;
}
this.ignoreHidden_ = false;
if (opt_options.ignoreHidden !== undefined) {
this.ignoreHidden_ = opt_options.ignoreHidden;
}
this.enableRetinaIcons_ = false;
if (opt_options.enableRetinaIcons !== undefined) {
this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
}
this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
this.clusterClass_ = opt_options.clusterClass || "cluster";
if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
// Try to avoid IE timeout when processing a huge number of markers:
this.batchSize_ = this.batchSizeIE_;
}
this.setupStyles_();
this.addMarkers(opt_markers, true);
this.setMap(map); // Note: this causes onAdd to be called
}
/**
* Implementation of the onAdd interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function () {
var cMarkerClusterer = this;
this.activeMap_ = this.getMap();
this.ready_ = true;
this.repaint();
// Add the map event listeners
this.listeners_ = [
google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
cMarkerClusterer.resetViewport_(false);
// Workaround for this Google bug: when map is at level 0 and "-" of
// zoom slider is clicked, a "zoom_changed" event is fired even though
// the map doesn't zoom out any further. In this situation, no "idle"
// event is triggered so the cluster markers that have been removed
// do not get redrawn. Same goes for a zoom in at maxZoom.
if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) {
google.maps.event.trigger(this, "idle");
}
}),
google.maps.event.addListener(this.getMap(), "idle", function () {
cMarkerClusterer.redraw_();
})
];
};
/**
* Implementation of the onRemove interface method.
* Removes map event listeners and all cluster icons from the DOM.
* All managed markers are also put back on the map.
* @ignore
*/
MarkerClusterer.prototype.onRemove = function () {
var i;
// Put all the managed markers back on the map:
for (i = 0; i < this.markers_.length; i++) {
if (this.markers_[i].getMap() !== this.activeMap_) {
this.markers_[i].setMap(this.activeMap_);
}
}
// Remove all clusters:
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Remove map event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
};
/**
* Implementation of the draw interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function () {};
/**
* Sets up the styles object.
*/
MarkerClusterer.prototype.setupStyles_ = function () {
var i, size;
if (this.styles_.length > 0) {
return;
}
for (i = 0; i < this.imageSizes_.length; i++) {
size = this.imageSizes_[i];
this.styles_.push({
url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fits the map to the bounds of the markers managed by the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function () {
var i;
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
this.getMap().fitBounds(bounds);
};
/**
* Returns the value of the <code>gridSize</code> property.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function () {
return this.gridSize_;
};
/**
* Sets the value of the <code>gridSize</code> property.
*
* @param {number} gridSize The grid size.
*/
MarkerClusterer.prototype.setGridSize = function (gridSize) {
this.gridSize_ = gridSize;
};
/**
* Returns the value of the <code>minimumClusterSize</code> property.
*
* @return {number} The minimum cluster size.
*/
MarkerClusterer.prototype.getMinimumClusterSize = function () {
return this.minClusterSize_;
};
/**
* Sets the value of the <code>minimumClusterSize</code> property.
*
* @param {number} minimumClusterSize The minimum cluster size.
*/
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
this.minClusterSize_ = minimumClusterSize;
};
/**
* Returns the value of the <code>maxZoom</code> property.
*
* @return {number} The maximum zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function () {
return this.maxZoom_;
};
/**
* Sets the value of the <code>maxZoom</code> property.
*
* @param {number} maxZoom The maximum zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Returns the value of the <code>styles</code> property.
*
* @return {Array} The array of styles defining the cluster markers to be used.
*/
MarkerClusterer.prototype.getStyles = function () {
return this.styles_;
};
/**
* Sets the value of the <code>styles</code> property.
*
* @param {Array.<ClusterIconStyle>} styles The array of styles to use.
*/
MarkerClusterer.prototype.setStyles = function (styles) {
this.styles_ = styles;
};
/**
* Returns the value of the <code>title</code> property.
*
* @return {string} The content of the title text.
*/
MarkerClusterer.prototype.getTitle = function () {
return this.title_;
};
/**
* Sets the value of the <code>title</code> property.
*
* @param {string} title The value of the title property.
*/
MarkerClusterer.prototype.setTitle = function (title) {
this.title_ = title;
};
/**
* Returns the value of the <code>zoomOnClick</code> property.
*
* @return {boolean} True if zoomOnClick property is set.
*/
MarkerClusterer.prototype.getZoomOnClick = function () {
return this.zoomOnClick_;
};
/**
* Sets the value of the <code>zoomOnClick</code> property.
*
* @param {boolean} zoomOnClick The value of the zoomOnClick property.
*/
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
this.zoomOnClick_ = zoomOnClick;
};
/**
* Returns the value of the <code>averageCenter</code> property.
*
* @return {boolean} True if averageCenter property is set.
*/
MarkerClusterer.prototype.getAverageCenter = function () {
return this.averageCenter_;
};
/**
* Sets the value of the <code>averageCenter</code> property.
*
* @param {boolean} averageCenter The value of the averageCenter property.
*/
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
this.averageCenter_ = averageCenter;
};
/**
* Returns the value of the <code>ignoreHidden</code> property.
*
* @return {boolean} True if ignoreHidden property is set.
*/
MarkerClusterer.prototype.getIgnoreHidden = function () {
return this.ignoreHidden_;
};
/**
* Sets the value of the <code>ignoreHidden</code> property.
*
* @param {boolean} ignoreHidden The value of the ignoreHidden property.
*/
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
this.ignoreHidden_ = ignoreHidden;
};
/**
* Returns the value of the <code>enableRetinaIcons</code> property.
*
* @return {boolean} True if enableRetinaIcons property is set.
*/
MarkerClusterer.prototype.getEnableRetinaIcons = function () {
return this.enableRetinaIcons_;
};
/**
* Sets the value of the <code>enableRetinaIcons</code> property.
*
* @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
*/
MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {
this.enableRetinaIcons_ = enableRetinaIcons;
};
/**
* Returns the value of the <code>imageExtension</code> property.
*
* @return {string} The value of the imageExtension property.
*/
MarkerClusterer.prototype.getImageExtension = function () {
return this.imageExtension_;
};
/**
* Sets the value of the <code>imageExtension</code> property.
*
* @param {string} imageExtension The value of the imageExtension property.
*/
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
this.imageExtension_ = imageExtension;
};
/**
* Returns the value of the <code>imagePath</code> property.
*
* @return {string} The value of the imagePath property.
*/
MarkerClusterer.prototype.getImagePath = function () {
return this.imagePath_;
};
/**
* Sets the value of the <code>imagePath</code> property.
*
* @param {string} imagePath The value of the imagePath property.
*/
MarkerClusterer.prototype.setImagePath = function (imagePath) {
this.imagePath_ = imagePath;
};
/**
* Returns the value of the <code>imageSizes</code> property.
*
* @return {Array} The value of the imageSizes property.
*/
MarkerClusterer.prototype.getImageSizes = function () {
return this.imageSizes_;
};
/**
* Sets the value of the <code>imageSizes</code> property.
*
* @param {Array} imageSizes The value of the imageSizes property.
*/
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
this.imageSizes_ = imageSizes;
};
/**
* Returns the value of the <code>calculator</code> property.
*
* @return {function} the value of the calculator property.
*/
MarkerClusterer.prototype.getCalculator = function () {
return this.calculator_;
};
/**
* Sets the value of the <code>calculator</code> property.
*
* @param {function(Array.<google.maps.Marker>, number)} calculator The value
* of the calculator property.
*/
MarkerClusterer.prototype.setCalculator = function (calculator) {
this.calculator_ = calculator;
};
/**
* Returns the value of the <code>batchSizeIE</code> property.
*
* @return {number} the value of the batchSizeIE property.
*/
MarkerClusterer.prototype.getBatchSizeIE = function () {
return this.batchSizeIE_;
};
/**
* Sets the value of the <code>batchSizeIE</code> property.
*
* @param {number} batchSizeIE The value of the batchSizeIE property.
*/
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
this.batchSizeIE_ = batchSizeIE;
};
/**
* Returns the value of the <code>clusterClass</code> property.
*
* @return {string} the value of the clusterClass property.
*/
MarkerClusterer.prototype.getClusterClass = function () {
return this.clusterClass_;
};
/**
* Sets the value of the <code>clusterClass</code> property.
*
* @param {string} clusterClass The value of the clusterClass property.
*/
MarkerClusterer.prototype.setClusterClass = function (clusterClass) {
this.clusterClass_ = clusterClass;
};
/**
* Returns the array of markers managed by the clusterer.
*
* @return {Array} The array of markers managed by the clusterer.
*/
MarkerClusterer.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the number of markers managed by the clusterer.
*
* @return {number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function () {
return this.markers_.length;
};
/**
* Returns the current array of clusters formed by the clusterer.
*
* @return {Array} The array of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getClusters = function () {
return this.clusters_;
};
/**
* Returns the number of clusters formed by the clusterer.
*
* @return {number} The number of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getTotalClusters = function () {
return this.clusters_.length;
};
/**
* Adds a marker to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Adds an array of markers to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
var key;
for (key in markers) {
if (markers.hasOwnProperty(key)) {
this.pushMarkerTo_(markers[key]);
}
}
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
// If the marker is draggable add a listener so we can update the clusters on the dragend:
if (marker.getDraggable()) {
var cMarkerClusterer = this;
google.maps.event.addListener(marker, "dragend", function () {
if (cMarkerClusterer.ready_) {
this.isAdded = false;
cMarkerClusterer.repaint();
}
});
}
marker.isAdded = false;
this.markers_.push(marker);
};
/**
* Removes a marker from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
* marker was removed from the clusterer.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if the marker was removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes an array of markers from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
* were removed from the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if markers were removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
var i, r;
var removed = false;
for (i = 0; i < markers.length; i++) {
r = this.removeMarker_(markers[i]);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
MarkerClusterer.prototype.removeMarker_ = function (marker) {
var i;
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
index = i;
break;
}
}
}
if (index === -1) {
// Marker is not in our list of markers, so do nothing:
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
return true;
};
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = [];
};
/**
* Recalculates and redraws all the marker clusters from scratch.
* Call this after changing any properties.
*/
MarkerClusterer.prototype.repaint = function () {
var oldClusters = this.clusters_.slice();
this.clusters_ = [];
this.resetViewport_(false);
this.redraw_();
// Remove the old clusters.
// Do it in a timeout to prevent blinking effect.
setTimeout(function () {
var i;
for (i = 0; i < oldClusters.length; i++) {
oldClusters[i].remove();
}
}, 0);
};
/**
* Returns the current bounds extended by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
* @ignore
*/
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Redraws all the clusters.
*/
MarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
for (i = 0; i < this.markers_.length; i++) {
marker = this.markers_[i];
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
};
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Determines if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringbegin", this);
if (typeof this.timerRefStatic !== "undefined") {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
for (i = iFirst; i < iLast; i++) {
marker = this.markers_[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringend", this);
}
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* The default function for determining the label text and style
* for a cluster icon.
*
* @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
* @param {number} numStyles The number of marker styles available.
* @return {ClusterIconInfo} The information resource for the cluster.
* @constant
* @ignore
*/
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index,
title: title
};
};
/**
* The number of markers to process in one batch.
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE = 2000;
/**
* The number of markers to process in one batch (IE only).
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE_IE = 500;
/**
* The default root name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m";
/**
* The default extension name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_EXTENSION = "png";
/**
* The default array of sizes for the marker cluster images.
*
* @type {Array.<number>}
* @constant
*/
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
/**
* @name MarkerWithLabel for V3
* @version 1.1.10 [April 8, 2014]
* @author Gary Little (inspired by code from Marc Ridey of Google).
* @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
* @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
* <code>google.maps.Marker</code> class.
* <p>
* MarkerWithLabel allows you to define markers with associated labels. As you would expect,
* if the marker is draggable, so too will be the label. In addition, a marker with a label
* responds to all mouse events in the same manner as a regular marker. It also fires mouse
* events and "property changed" events just as a regular marker would. Version 1.1 adds
* support for the raiseOnDrag feature introduced in API V3.3.
* <p>
* If you drag a marker by its label, you can cancel the drag and return the marker to its
* original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
* itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
*/
/*!
*
* 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.
*/
/*jslint browser:true */
/*global document,google */
/**
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
* @private
*/
function inherits(childCtor, parentCtor) {
/* @constructor */
function tempCtor() {}
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/* @override */
childCtor.prototype.constructor = childCtor;
}
/**
* This constructor creates a label and associates it with a marker.
* It is for the private use of the MarkerWithLabel class.
* @constructor
* @param {Marker} marker The marker with which the label is to be associated.
* @param {string} crossURL The URL of the cross image =.
* @param {string} handCursor The URL of the hand cursor.
* @private
*/
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.setAttribute("onselectstart", "return false;");
this.eventDiv_.setAttribute("ondragstart", "return false;");
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
inherits(MarkerLabel_, google.maps.OverlayView);
/**
* Returns the DIV for the cross used when dragging a marker when the
* raiseOnDrag parameter set to true. One cross is shared with all markers.
* @param {string} crossURL The URL of the cross image =.
* @private
*/
MarkerLabel_.getSharedCross = function (crossURL) {
var div;
if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") {
div = document.createElement("img");
div.style.cssText = "position: absolute; z-index: 1000002; display: none;";
// Hopefully Google never changes the standard "X" attributes:
div.style.marginLeft = "-8px";
div.style.marginTop = "-9px";
div.src = crossURL;
MarkerLabel_.getSharedCross.crossDiv = div;
}
return MarkerLabel_.getSharedCross.crossDiv;
};
/**
* Adds the DIV representing the label to the DOM. This method is called
* automatically when the marker's <code>setMap</code> method is called.
* @private
*/
MarkerLabel_.prototype.onAdd = function () {
var me = this;
var cMouseIsDown = false;
var cDraggingLabel = false;
var cSavedZIndex;
var cLatOffset, cLngOffset;
var cIgnoreClick;
var cRaiseEnabled;
var cStartPosition;
var cStartCenter;
// Constants:
var cRaiseOffset = 20;
var cDraggingCursor = "url(" + this.handCursorURL_ + ")";
// Stops all processing of an event.
//
var cAbortEvent = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
var cStopBounce = function () {
me.marker_.setAnimation(null);
};
this.getPanes().overlayImage.appendChild(this.labelDiv_);
this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_);
// One cross is shared with all markers, so only add it once:
if (typeof MarkerLabel_.getSharedCross.processed === "undefined") {
this.getPanes().overlayImage.appendChild(this.crossDiv_);
MarkerLabel_.getSharedCross.processed = true;
}
this.listeners_ = [
google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
this.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseover", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) {
if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {
this.style.cursor = me.marker_.getCursor();
google.maps.event.trigger(me.marker_, "mouseout", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) {
cDraggingLabel = false;
if (me.marker_.getDraggable()) {
cMouseIsDown = true;
this.style.cursor = cDraggingCursor;
}
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "mousedown", e);
cAbortEvent(e); // Prevent map pan when starting a drag on a label
}
}),
google.maps.event.addDomListener(document, "mouseup", function (mEvent) {
var position;
if (cMouseIsDown) {
cMouseIsDown = false;
me.eventDiv_.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseup", mEvent);
}
if (cDraggingLabel) {
if (cRaiseEnabled) { // Lower the marker & label
position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());
position.y += cRaiseOffset;
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
// This is not the same bouncing style as when the marker portion is dragged,
// but it will have to do:
try { // Will fail if running Google Maps API earlier than V3.3
me.marker_.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(cStopBounce, 1406);
} catch (e) {}
}
me.crossDiv_.style.display = "none";
me.marker_.setZIndex(cSavedZIndex);
cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag
cDraggingLabel = false;
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragend", mEvent);
}
}),
google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) {
var position;
if (cMouseIsDown) {
if (cDraggingLabel) {
// Change the reported location from the mouse position to the marker position:
mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);
position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);
if (cRaiseEnabled) {
me.crossDiv_.style.left = position.x + "px";
me.crossDiv_.style.top = position.y + "px";
me.crossDiv_.style.display = "";
position.y -= cRaiseOffset;
}
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly
me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px";
}
google.maps.event.trigger(me.marker_, "drag", mEvent);
} else {
// Calculate offsets from the click point to the marker position:
cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();
cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();
cSavedZIndex = me.marker_.getZIndex();
cStartPosition = me.marker_.getPosition();
cStartCenter = me.marker_.getMap().getCenter();
cRaiseEnabled = me.marker_.get("raiseOnDrag");
cDraggingLabel = true;
me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragstart", mEvent);
}
}
}),
google.maps.event.addDomListener(document, "keydown", function (e) {
if (cDraggingLabel) {
if (e.keyCode === 27) { // Esc key
cRaiseEnabled = false;
me.marker_.setPosition(cStartPosition);
me.marker_.getMap().setCenter(cStartCenter);
google.maps.event.trigger(document, "mouseup", e);
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "click", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
if (cIgnoreClick) { // Ignore the click reported when a label drag ends
cIgnoreClick = false;
} else {
google.maps.event.trigger(me.marker_, "click", e);
cAbortEvent(e); // Prevent click from being passed on to map
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "dblclick", e);
cAbortEvent(e); // Prevent map zoom when double-clicking on a label
}
}),
google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) {
if (!cDraggingLabel) {
cRaiseEnabled = this.get("raiseOnDrag");
}
}),
google.maps.event.addListener(this.marker_, "drag", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(cRaiseOffset);
// During a drag, the marker's z-index is temporarily set to 1000000 to
// ensure it appears above all other markers. Also set the label's z-index
// to 1000000 (plus or minus 1 depending on whether the label is supposed
// to be above or below the marker).
me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1);
}
}
}),
google.maps.event.addListener(this.marker_, "dragend", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(0); // Also restores z-index of label
}
}
}),
google.maps.event.addListener(this.marker_, "position_changed", function () {
me.setPosition();
}),
google.maps.event.addListener(this.marker_, "zindex_changed", function () {
me.setZIndex();
}),
google.maps.event.addListener(this.marker_, "visible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "labelvisible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "title_changed", function () {
me.setTitle();
}),
google.maps.event.addListener(this.marker_, "labelcontent_changed", function () {
me.setContent();
}),
google.maps.event.addListener(this.marker_, "labelanchor_changed", function () {
me.setAnchor();
}),
google.maps.event.addListener(this.marker_, "labelclass_changed", function () {
me.setStyles();
}),
google.maps.event.addListener(this.marker_, "labelstyle_changed", function () {
me.setStyles();
})
];
};
/**
* Removes the DIV for the label from the DOM. It also removes all event handlers.
* This method is called automatically when the marker's <code>setMap(null)</code>
* method is called.
* @private
*/
MarkerLabel_.prototype.onRemove = function () {
var i;
this.labelDiv_.parentNode.removeChild(this.labelDiv_);
this.eventDiv_.parentNode.removeChild(this.eventDiv_);
// Remove event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
/**
* Draws the label on the map.
* @private
*/
MarkerLabel_.prototype.draw = function () {
this.setContent();
this.setTitle();
this.setStyles();
};
/**
* Sets the content of the label.
* The content can be plain text or an HTML DOM node.
* @private
*/
MarkerLabel_.prototype.setContent = function () {
var content = this.marker_.get("labelContent");
if (typeof content.nodeType === "undefined") {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
} else {
this.labelDiv_.innerHTML = ""; // Remove current content
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.eventDiv_.innerHTML = ""; // Remove current content
this.eventDiv_.appendChild(content);
}
};
/**
* Sets the content of the tool tip for the label. It is
* always set to be the same as for the marker itself.
* @private
*/
MarkerLabel_.prototype.setTitle = function () {
this.eventDiv_.title = this.marker_.getTitle() || "";
};
/**
* Sets the style of the label by setting the style sheet and applying
* other specific styles requested.
* @private
*/
MarkerLabel_.prototype.setStyles = function () {
var i, labelStyle;
// Apply style values from the style sheet defined in the labelClass parameter:
this.labelDiv_.className = this.marker_.get("labelClass");
this.eventDiv_.className = this.labelDiv_.className;
// Clear existing inline style values:
this.labelDiv_.style.cssText = "";
this.eventDiv_.style.cssText = "";
// Apply style values defined in the labelStyle parameter:
labelStyle = this.marker_.get("labelStyle");
for (i in labelStyle) {
if (labelStyle.hasOwnProperty(i)) {
this.labelDiv_.style[i] = labelStyle[i];
this.eventDiv_.style[i] = labelStyle[i];
}
}
this.setMandatoryStyles();
};
/**
* Sets the mandatory styles to the DIV representing the label as well as to the
* associated event DIV. This includes setting the DIV position, z-index, and visibility.
* @private
*/
MarkerLabel_.prototype.setMandatoryStyles = function () {
this.labelDiv_.style.position = "absolute";
this.labelDiv_.style.overflow = "hidden";
// Make sure the opacity setting causes the desired effect on MSIE:
if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") {
this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\"";
this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")";
}
this.eventDiv_.style.position = this.labelDiv_.style.position;
this.eventDiv_.style.overflow = this.labelDiv_.style.overflow;
this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE
this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\"";
this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE
this.setAnchor();
this.setPosition(); // This also updates z-index, if necessary.
this.setVisible();
};
/**
* Sets the anchor point of the label.
* @private
*/
MarkerLabel_.prototype.setAnchor = function () {
var anchor = this.marker_.get("labelAnchor");
this.labelDiv_.style.marginLeft = -anchor.x + "px";
this.labelDiv_.style.marginTop = -anchor.y + "px";
this.eventDiv_.style.marginLeft = -anchor.x + "px";
this.eventDiv_.style.marginTop = -anchor.y + "px";
};
/**
* Sets the position of the label. The z-index is also updated, if necessary.
* @private
*/
MarkerLabel_.prototype.setPosition = function (yOffset) {
var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());
if (typeof yOffset === "undefined") {
yOffset = 0;
}
this.labelDiv_.style.left = Math.round(position.x) + "px";
this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px";
this.eventDiv_.style.left = this.labelDiv_.style.left;
this.eventDiv_.style.top = this.labelDiv_.style.top;
this.setZIndex();
};
/**
* Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index
* of the label is set to the vertical coordinate of the label. This is in keeping with the default
* stacking order for Google Maps: markers to the south are in front of markers to the north.
* @private
*/
MarkerLabel_.prototype.setZIndex = function () {
var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1);
if (typeof this.marker_.getZIndex() === "undefined") {
this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
} else {
this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
}
};
/**
* Sets the visibility of the label. The label is visible only if the marker itself is
* visible (i.e., its visible property is true) and the labelVisible property is true.
* @private
*/
MarkerLabel_.prototype.setVisible = function () {
if (this.marker_.get("labelVisible")) {
this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none";
} else {
this.labelDiv_.style.display = "none";
}
this.eventDiv_.style.display = this.labelDiv_.style.display;
};
/**
* @name MarkerWithLabelOptions
* @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.
* The properties available are the same as for <code>google.maps.Marker</code> with the addition
* of the properties listed below. To change any of these additional properties after the labeled
* marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>.
* <p>
* When any of these properties changes, a property changed event is fired. The names of these
* events are derived from the name of the property and are of the form <code>propertyname_changed</code>.
* For example, if the content of the label changes, a <code>labelcontent_changed</code> event
* is fired.
* <p>
* @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).
* @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so
* that its top left corner is positioned at the anchor point of the associated marker. Use this
* property to change the anchor point of the label. For example, to center a 50px-wide label
* beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>.
* (Note: x-values increase to the right and y-values increase to the top.)
* @property {string} [labelClass] The name of the CSS class defining the styles for the label.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {Object} [labelStyle] An object literal whose properties define specific CSS
* style values to be applied to the label. Style values defined here override those that may
* be defined in the <code>labelClass</code> style sheet. If this property is changed after the
* label has been created, all previously set styles (except those defined in the style sheet)
* are removed from the label before the new style values are applied.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its
* associated marker should appear in the background (i.e., in a plane below the marker).
* The default is <code>false</code>, which causes the label to appear in the foreground.
* @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.
* The default is <code>true</code>. Note that even if <code>labelVisible</code> is
* <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also
* visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>).
* @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be
* raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is
* being created and a version of Google Maps API earlier than V3.3 is being used, this property
* must be set to <code>false</code>.
* @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the
* marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel,
* so the value of this parameter is always forced to <code>false</code>.
* @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"]
* The URL of the cross image to be displayed while dragging a marker.
* @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"]
* The URL of the cursor to be displayed while dragging a marker.
*/
/**
* Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.
* @constructor
* @param {MarkerWithLabelOptions} [opt_options] The optional parameters.
*/
function MarkerWithLabel(opt_options) {
opt_options = opt_options || {};
opt_options.labelContent = opt_options.labelContent || "";
opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);
opt_options.labelClass = opt_options.labelClass || "markerLabels";
opt_options.labelStyle = opt_options.labelStyle || {};
opt_options.labelInBackground = opt_options.labelInBackground || false;
if (typeof opt_options.labelVisible === "undefined") {
opt_options.labelVisible = true;
}
if (typeof opt_options.raiseOnDrag === "undefined") {
opt_options.raiseOnDrag = true;
}
if (typeof opt_options.clickable === "undefined") {
opt_options.clickable = true;
}
if (typeof opt_options.draggable === "undefined") {
opt_options.draggable = false;
}
if (typeof opt_options.optimized === "undefined") {
opt_options.optimized = false;
}
opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png";
opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur";
opt_options.optimized = false; // Optimized rendering is not supported
this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker
// Call the parent constructor. It calls Marker.setValues to initialize, so all
// the new parameters are conveniently saved and can be accessed with get/set.
// Marker.set triggers a property changed event (called "propertyname_changed")
// that the marker label listens for in order to react to state changes.
google.maps.Marker.apply(this, arguments);
}
inherits(MarkerWithLabel, google.maps.Marker);
/**
* Overrides the standard Marker setMap function.
* @param {Map} theMap The map to which the marker is to be added.
* @private
*/
MarkerWithLabel.prototype.setMap = function (theMap) {
// Call the inherited function...
google.maps.Marker.prototype.setMap.apply(this, arguments);
// ... then deal with the label:
this.label.setMap(theMap);
};
//END REPLACE
window.InfoBox = InfoBox;
window.Cluster = Cluster;
window.ClusterIcon = ClusterIcon;
window.MarkerClusterer = MarkerClusterer;
window.MarkerLabel_ = MarkerLabel_;
window.MarkerWithLabel = MarkerWithLabel;
})
};
});
;/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapDataStructures', function() {
return {
Graph: __webpack_require__(1).Graph,
Queue: __webpack_require__(1).Queue
};
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
(function() {
module.exports = {
Graph: __webpack_require__(2),
Heap: __webpack_require__(3),
LinkedList: __webpack_require__(4),
Map: __webpack_require__(5),
Queue: __webpack_require__(6),
RedBlackTree: __webpack_require__(7),
Trie: __webpack_require__(8)
};
}).call(this);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/*
Graph implemented as a modified incidence list. O(1) for every typical
operation except `removeNode()` at O(E) where E is the number of edges.
## Overview example:
```js
var graph = new Graph;
graph.addNode('A'); // => a node object. For more info, log the output or check
// the documentation for addNode
graph.addNode('B');
graph.addNode('C');
graph.addEdge('A', 'C'); // => an edge object
graph.addEdge('A', 'B');
graph.getEdge('B', 'A'); // => undefined. Directed edge!
graph.getEdge('A', 'B'); // => the edge object previously added
graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property
// of an edge object. Feel free to attach
// other properties
graph.getInEdgesOf('B'); // => array of edge objects, in this case only one;
// connecting A to B
graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C
graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward
// the node itself are only counted once
forEachNode(function(nodeObject) {
console.log(node);
});
forEachEdge(function(edgeObject) {
console.log(edgeObject);
});
graph.removeNode('C'); // => 'C'. The edge between A and C also removed
graph.removeEdge('A', 'B'); // => the edge object removed
```
## Properties:
- nodeSize: total number of nodes.
- edgeSize: total number of edges.
*/
(function() {
var Graph,
__hasProp = {}.hasOwnProperty;
Graph = (function() {
function Graph() {
this._nodes = {};
this.nodeSize = 0;
this.edgeSize = 0;
}
Graph.prototype.addNode = function(id) {
/*
The `id` is a unique identifier for the node, and should **not** change
after it's added. It will be used for adding, retrieving and deleting
related edges too.
**Note** that, internally, the ids are kept in an object. JavaScript's
object hashes the id `'2'` and `2` to the same key, so please stick to a
simple id data type such as number or string.
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs. **Undefined if node id already exists**,
as to avoid accidental overrides.
*/
if (!this._nodes[id]) {
this.nodeSize++;
return this._nodes[id] = {
_outEdges: {},
_inEdges: {}
};
}
};
Graph.prototype.getNode = function(id) {
/*
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs.
*/
return this._nodes[id];
};
Graph.prototype.removeNode = function(id) {
/*
_Returns:_ the node object removed, or undefined if it didn't exist in the
first place.
*/
var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1;
nodeToRemove = this._nodes[id];
if (!nodeToRemove) {
return;
} else {
_ref = nodeToRemove._outEdges;
for (outEdgeId in _ref) {
if (!__hasProp.call(_ref, outEdgeId)) continue;
this.removeEdge(id, outEdgeId);
}
_ref1 = nodeToRemove._inEdges;
for (inEdgeId in _ref1) {
if (!__hasProp.call(_ref1, inEdgeId)) continue;
this.removeEdge(inEdgeId, id);
}
this.nodeSize--;
delete this._nodes[id];
}
return nodeToRemove;
};
Graph.prototype.addEdge = function(fromId, toId, weight) {
var edgeToAdd, fromNode, toNode;
if (weight == null) {
weight = 1;
}
/*
`fromId` and `toId` are the node id specified when it was created using
`addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively
makes this an unweighted graph. Under the hood, `weight` is just a normal
property of the edge object.
_Returns:_ the edge object created. Feel free to attach additional custom
properties on it for graph algorithms' needs. **Or undefined** if the nodes
of id `fromId` or `toId` aren't found, or if an edge already exists between
the two nodes.
*/
if (this.getEdge(fromId, toId)) {
return;
}
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
return;
}
edgeToAdd = {
weight: weight
};
fromNode._outEdges[toId] = edgeToAdd;
toNode._inEdges[fromId] = edgeToAdd;
this.edgeSize++;
return edgeToAdd;
};
Graph.prototype.getEdge = function(fromId, toId) {
/*
_Returns:_ the edge object, or undefined if the nodes of id `fromId` or
`toId` aren't found.
*/
var fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
} else {
return fromNode._outEdges[toId];
}
};
Graph.prototype.removeEdge = function(fromId, toId) {
/*
_Returns:_ the edge object removed, or undefined of edge wasn't found.
*/
var edgeToDelete, fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
edgeToDelete = this.getEdge(fromId, toId);
if (!edgeToDelete) {
return;
}
delete fromNode._outEdges[toId];
delete toNode._inEdges[fromId];
this.edgeSize--;
return edgeToDelete;
};
Graph.prototype.getInEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that are directed toward the node, or
empty array if no such edge or node exists.
*/
var fromId, inEdges, toNode, _ref;
toNode = this._nodes[nodeId];
inEdges = [];
_ref = toNode != null ? toNode._inEdges : void 0;
for (fromId in _ref) {
if (!__hasProp.call(_ref, fromId)) continue;
inEdges.push(this.getEdge(fromId, nodeId));
}
return inEdges;
};
Graph.prototype.getOutEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that go out of the node, or empty array
if no such edge or node exists.
*/
var fromNode, outEdges, toId, _ref;
fromNode = this._nodes[nodeId];
outEdges = [];
_ref = fromNode != null ? fromNode._outEdges : void 0;
for (toId in _ref) {
if (!__hasProp.call(_ref, toId)) continue;
outEdges.push(this.getEdge(nodeId, toId));
}
return outEdges;
};
Graph.prototype.getAllEdgesOf = function(nodeId) {
/*
**Note:** not the same as concatenating `getInEdgesOf()` and
`getOutEdgesOf()`. Some nodes might have an edge pointing toward itself.
This method solves that duplication.
_Returns:_ an array of edge objects linked to the node, no matter if they're
outgoing or coming. Duplicate edge created by self-pointing nodes are
removed. Only one copy stays. Empty array if node has no edge.
*/
var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1;
inEdges = this.getInEdgesOf(nodeId);
outEdges = this.getOutEdgesOf(nodeId);
if (inEdges.length === 0) {
return outEdges;
}
selfEdge = this.getEdge(nodeId, nodeId);
for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (inEdges[i] === selfEdge) {
_ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1];
inEdges.pop();
break;
}
}
return inEdges.concat(outEdges);
};
Graph.prototype.forEachNode = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each node once.
Pass a function of the form `fn(nodeObject, nodeId)`.
_Returns:_ undefined.
*/
var nodeId, nodeObject, _ref;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
operation(nodeObject, nodeId);
}
};
Graph.prototype.forEachEdge = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each edge once.
Pass a function of the form `fn(edgeObject)`.
_Returns:_ undefined.
*/
var edgeObject, nodeId, nodeObject, toId, _ref, _ref1;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
_ref1 = nodeObject._outEdges;
for (toId in _ref1) {
if (!__hasProp.call(_ref1, toId)) continue;
edgeObject = _ref1[toId];
operation(edgeObject);
}
}
};
return Graph;
})();
module.exports = Graph;
}).call(this);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/*
Minimum heap, i.e. smallest node at root.
**Note:** does not accept null or undefined. This is by design. Those values
cause comparison problems and might report false negative during extraction.
## Overview example:
```js
var heap = new Heap([5, 6, 3, 4]);
heap.add(10); // => 10
heap.removeMin(); // => 3
heap.peekMin(); // => 4
```
## Properties:
- size: total number of items.
*/
(function() {
var Heap, _leftChild, _parent, _rightChild;
Heap = (function() {
function Heap(dataToHeapify) {
var i, item, _i, _j, _len, _ref;
if (dataToHeapify == null) {
dataToHeapify = [];
}
/*
Pass an optional array to be heapified. Takes only O(n) time.
*/
this._data = [void 0];
for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) {
item = dataToHeapify[_i];
if (item != null) {
this._data.push(item);
}
}
if (this._data.length > 1) {
for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) {
this._upHeap(i);
}
}
this.size = this._data.length - 1;
}
Heap.prototype.add = function(value) {
/*
**Remember:** rejects null and undefined for mentioned reasons.
_Returns:_ the value added.
*/
if (value == null) {
return;
}
this._data.push(value);
this._upHeap(this._data.length - 1);
this.size++;
return value;
};
Heap.prototype.removeMin = function() {
/*
_Returns:_ the smallest item (the root).
*/
var min;
if (this._data.length === 1) {
return;
}
this.size--;
if (this._data.length === 2) {
return this._data.pop();
}
min = this._data[1];
this._data[1] = this._data.pop();
this._downHeap();
return min;
};
Heap.prototype.peekMin = function() {
/*
Check the smallest item without removing it.
_Returns:_ the smallest item (the root).
*/
return this._data[1];
};
Heap.prototype._upHeap = function(index) {
var valueHolder, _ref;
valueHolder = this._data[index];
while (this._data[index] < this._data[_parent(index)] && index > 1) {
_ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1];
index = _parent(index);
}
};
Heap.prototype._downHeap = function() {
var currentIndex, smallerChildIndex, _ref;
currentIndex = 1;
while (_leftChild(currentIndex < this._data.length)) {
smallerChildIndex = _leftChild(currentIndex);
if (smallerChildIndex < this._data.length - 1) {
if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) {
smallerChildIndex = _rightChild(currentIndex);
}
}
if (this._data[smallerChildIndex] < this._data[currentIndex]) {
_ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1];
currentIndex = smallerChildIndex;
} else {
break;
}
}
};
return Heap;
})();
_parent = function(index) {
return index >> 1;
};
_leftChild = function(index) {
return index << 1;
};
_rightChild = function(index) {
return (index << 1) + 1;
};
module.exports = Heap;
}).call(this);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
Doubly Linked.
## Overview example:
```js
var list = new LinkedList([5, 4, 9]);
list.add(12); // => 12
list.head.next.value; // => 4
list.tail.value; // => 12
list.at(-1); // => 12
list.removeAt(2); // => 9
list.remove(4); // => 4
list.indexOf(5); // => 0
list.add(5, 1); // => 5. Second 5 at position 1.
list.indexOf(5, 1); // => 1
```
## Properties:
- head: first item.
- tail: last item.
- size: total number of items.
- item.value: value passed to the item when calling `add()`.
- item.prev: previous item.
- item.next: next item.
*/
(function() {
var LinkedList;
LinkedList = (function() {
function LinkedList(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Can pass an array of elements to link together during `new LinkedList()`
initiation.
*/
this.head = {
prev: void 0,
value: void 0,
next: void 0
};
this.tail = {
prev: void 0,
value: void 0,
next: void 0
};
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
this.add(value);
}
}
LinkedList.prototype.at = function(position) {
/*
Get the item at `position` (optional). Accepts negative index:
```js
myList.at(-1); // Returns the last element.
```
However, passing a negative index that surpasses the boundary will return
undefined:
```js
myList = new LinkedList([2, 6, 8, 3])
myList.at(-5); // Undefined.
myList.at(-4); // 2.
```
_Returns:_ item gotten, or undefined if not found.
*/
var currentNode, i, _i, _j, _ref;
if (!((-this.size <= position && position < this.size))) {
return;
}
position = this._adjust(position);
if (position * 2 < this.size) {
currentNode = this.head;
for (i = _i = 1; _i <= position; i = _i += 1) {
currentNode = currentNode.next;
}
} else {
currentNode = this.tail;
for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) {
currentNode = currentNode.prev;
}
}
return currentNode;
};
LinkedList.prototype.add = function(value, position) {
var currentNode, nodeToAdd, _ref, _ref1, _ref2;
if (position == null) {
position = this.size;
}
/*
Add a new item at `position` (optional). Defaults to adding at the end.
`position`, just like in `at()`, can be negative (within the negative
boundary). Position specifies the place the value's going to be, and the old
node will be pushed higher. `add(-2)` on list of size 7 is the same as
`add(5)`.
_Returns:_ item added.
*/
if (!((-this.size <= position && position <= this.size))) {
return;
}
nodeToAdd = {
value: value
};
position = this._adjust(position);
if (this.size === 0) {
this.head = nodeToAdd;
} else {
if (position === 0) {
_ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2];
} else {
currentNode = this.at(position - 1);
_ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3];
}
}
if (position === this.size) {
this.tail = nodeToAdd;
}
this.size++;
return value;
};
LinkedList.prototype.removeAt = function(position) {
var currentNode, valueToReturn, _ref;
if (position == null) {
position = this.size - 1;
}
/*
Remove an item at index `position` (optional). Defaults to the last item.
Index can be negative (within the boundary).
_Returns:_ item removed.
*/
if (!((-this.size <= position && position < this.size))) {
return;
}
if (this.size === 0) {
return;
}
position = this._adjust(position);
if (this.size === 1) {
valueToReturn = this.head.value;
this.head.value = this.tail.value = void 0;
} else {
if (position === 0) {
valueToReturn = this.head.value;
this.head = this.head.next;
this.head.prev = void 0;
} else {
currentNode = this.at(position);
valueToReturn = currentNode.value;
currentNode.prev.next = currentNode.next;
if ((_ref = currentNode.next) != null) {
_ref.prev = currentNode.prev;
}
if (position === this.size - 1) {
this.tail = currentNode.prev;
}
}
}
this.size--;
return valueToReturn;
};
LinkedList.prototype.remove = function(value) {
/*
Remove the item using its value instead of position. **Will remove the fist
occurrence of `value`.**
_Returns:_ the value, or undefined if value's not found.
*/
var currentNode;
if (value == null) {
return;
}
currentNode = this.head;
while (currentNode && currentNode.value !== value) {
currentNode = currentNode.next;
}
if (!currentNode) {
return;
}
if (this.size === 1) {
this.head.value = this.tail.value = void 0;
} else if (currentNode === this.head) {
this.head = this.head.next;
this.head.prev = void 0;
} else if (currentNode === this.tail) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else {
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
}
this.size--;
return value;
};
LinkedList.prototype.indexOf = function(value, startingPosition) {
var currentNode, position;
if (startingPosition == null) {
startingPosition = 0;
}
/*
Find the index of an item, similarly to `array.indexOf()`. Defaults to start
searching from the beginning, by can start at another position by passing
`startingPosition`. This parameter can also be negative; but unlike the
other methods of this class, `startingPosition` (optional) can be as small
as desired; a value of -999 for a list of size 5 will start searching
normally, at the beginning.
**Note:** searches forwardly, **not** backwardly, i.e:
```js
var myList = new LinkedList([2, 3, 1, 4, 3, 5])
myList.indexOf(3, -3); // Returns 4, not 1
```
_Returns:_ index of item found, or -1 if not found.
*/
if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) {
return -1;
}
startingPosition = Math.max(0, this._adjust(startingPosition));
currentNode = this.at(startingPosition);
position = startingPosition;
while (currentNode) {
if (currentNode.value === value) {
break;
}
currentNode = currentNode.next;
position++;
}
if (position === this.size) {
return -1;
} else {
return position;
}
};
LinkedList.prototype._adjust = function(position) {
if (position < 0) {
return this.size + position;
} else {
return position;
}
};
return LinkedList;
})();
module.exports = LinkedList;
}).call(this);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/*
Kind of a stopgap measure for the upcoming [JavaScript
Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets)
**Note:** due to JavaScript's limitations, hashing something other than Boolean,
Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a
hidden unique property into the object. This means `set`, `get`, `has` and
`delete` must employ the same object, and not a mere identical copy as in the
case of, say, a string.
## Overview example:
```js
var map = new Map({'alice': 'wonderland', 20: 'ok'});
map.set('20', 5); // => 5
map.get('20'); // => 5
map.has('alice'); // => true
map.delete(20) // => true
var arr = [1, 2];
map.add(arr, 'goody'); // => 'goody'
map.has(arr); // => true
map.has([1, 2]); // => false. Needs to compare by reference
map.forEach(function(key, value) {
console.log(key, value);
});
```
## Properties:
- size: The total number of `(key, value)` pairs.
*/
(function() {
var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType,
__hasProp = {}.hasOwnProperty;
SPECIAL_TYPE_KEY_PREFIX = '_mapId_';
Map = (function() {
Map._mapIdTracker = 0;
Map._newMapId = function() {
return this._mapIdTracker++;
};
function Map(objectToMap) {
/*
Pass an optional object whose (key, value) pair will be hashed. **Careful**
not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's
native object behavior will crush the first 5 property before it gets to
constructor.
*/
var key, value;
this._content = {};
this._itemId = 0;
this._id = Map._newMapId();
this.size = 0;
for (key in objectToMap) {
if (!__hasProp.call(objectToMap, key)) continue;
value = objectToMap[key];
this.set(key, value);
}
}
Map.prototype.hash = function(key, makeHash) {
var propertyForMap, type;
if (makeHash == null) {
makeHash = false;
}
/*
The hash function for hashing keys is public. Feel free to replace it with
your own. The `makeHash` parameter is optional and accepts a boolean
(defaults to `false`) indicating whether or not to produce a new hash (for
the first use, naturally).
_Returns:_ the hash.
*/
type = _extractDataType(key);
if (_isSpecialType(key)) {
propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id;
if (makeHash && !key[propertyForMap]) {
key[propertyForMap] = this._itemId++;
}
return propertyForMap + '_' + key[propertyForMap];
} else {
return type + '_' + key;
}
};
Map.prototype.set = function(key, value) {
/*
_Returns:_ value.
*/
if (!this.has(key)) {
this.size++;
}
this._content[this.hash(key, true)] = [value, key];
return value;
};
Map.prototype.get = function(key) {
/*
_Returns:_ value corresponding to the key, or undefined if not found.
*/
var _ref;
return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0;
};
Map.prototype.has = function(key) {
/*
Check whether a value exists for the key.
_Returns:_ true or false.
*/
return this.hash(key) in this._content;
};
Map.prototype["delete"] = function(key) {
/*
Remove the (key, value) pair.
_Returns:_ **true or false**. Unlike most of this library, this method
doesn't return the deleted value. This is so that it conforms to the future
JavaScript `map.delete()`'s behavior.
*/
var hashedKey;
hashedKey = this.hash(key);
if (hashedKey in this._content) {
delete this._content[hashedKey];
if (_isSpecialType(key)) {
delete key[SPECIAL_TYPE_KEY_PREFIX + this._id];
}
this.size--;
return true;
}
return false;
};
Map.prototype.forEach = function(operation) {
/*
Traverse through the map. Pass a function of the form `fn(key, value)`.
_Returns:_ undefined.
*/
var key, value, _ref;
_ref = this._content;
for (key in _ref) {
if (!__hasProp.call(_ref, key)) continue;
value = _ref[key];
operation(value[1], value[0]);
}
};
return Map;
})();
_isSpecialType = function(key) {
var simpleHashableTypes, simpleType, type, _i, _len;
simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function'];
type = _extractDataType(key);
for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) {
simpleType = simpleHashableTypes[_i];
if (type === simpleType) {
return false;
}
}
return true;
};
_extractDataType = function(type) {
return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1];
};
module.exports = Map;
}).call(this);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*
Amortized O(1) dequeue!
## Overview example:
```js
var queue = new Queue([1, 6, 4]);
queue.enqueue(10); // => 10
queue.dequeue(); // => 1
queue.dequeue(); // => 6
queue.dequeue(); // => 4
queue.peek(); // => 10
queue.dequeue(); // => 10
queue.peek(); // => undefined
```
## Properties:
- size: The total number of items.
*/
(function() {
var Queue;
Queue = (function() {
function Queue(initialArray) {
if (initialArray == null) {
initialArray = [];
}
/*
Pass an optional array to be transformed into a queue. The item at index 0
is the first to be dequeued.
*/
this._content = initialArray;
this._dequeueIndex = 0;
this.size = this._content.length;
}
Queue.prototype.enqueue = function(item) {
/*
_Returns:_ the item.
*/
this.size++;
this._content.push(item);
return item;
};
Queue.prototype.dequeue = function() {
/*
_Returns:_ the dequeued item.
*/
var itemToDequeue;
if (this.size === 0) {
return;
}
this.size--;
itemToDequeue = this._content[this._dequeueIndex];
this._dequeueIndex++;
if (this._dequeueIndex * 2 > this._content.length) {
this._content = this._content.slice(this._dequeueIndex);
this._dequeueIndex = 0;
}
return itemToDequeue;
};
Queue.prototype.peek = function() {
/*
Check the next item to be dequeued, without removing it.
_Returns:_ the item.
*/
return this._content[this._dequeueIndex];
};
return Queue;
})();
module.exports = Queue;
}).call(this);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*
Credit to Wikipedia's article on [Red-black
tree](http://en.wikipedia.org/wiki/Red–black_tree)
**Note:** doesn't handle duplicate entries, undefined and null. This is by
design.
## Overview example:
```js
var rbt = new RedBlackTree([7, 5, 1, 8]);
rbt.add(2); // => 2
rbt.add(10); // => 10
rbt.has(5); // => true
rbt.peekMin(); // => 1
rbt.peekMax(); // => 10
rbt.removeMin(); // => 1
rbt.removeMax(); // => 10
rbt.remove(8); // => 8
```
## Properties:
- size: The total number of items.
*/
(function() {
var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf;
NODE_FOUND = 0;
NODE_TOO_BIG = 1;
NODE_TOO_SMALL = 2;
STOP_SEARCHING = 3;
RED = 1;
BLACK = 2;
RedBlackTree = (function() {
function RedBlackTree(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Pass an optional array to be turned into binary tree. **Note:** does not
accept duplicate, undefined and null.
*/
this._root;
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
if (value != null) {
this.add(value);
}
}
}
RedBlackTree.prototype.add = function(value) {
/*
Again, make sure to not pass a value already in the tree, or undefined, or
null.
_Returns:_ value added.
*/
var currentNode, foundNode, nodeToInsert, _ref;
if (value == null) {
return;
}
this.size++;
nodeToInsert = {
value: value,
_color: RED
};
if (!this._root) {
this._root = nodeToInsert;
} else {
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else {
if (value < node.value) {
if (node._left) {
return NODE_TOO_BIG;
} else {
nodeToInsert._parent = node;
node._left = nodeToInsert;
return STOP_SEARCHING;
}
} else {
if (node._right) {
return NODE_TOO_SMALL;
} else {
nodeToInsert._parent = node;
node._right = nodeToInsert;
return STOP_SEARCHING;
}
}
}
});
if (foundNode != null) {
return;
}
}
currentNode = nodeToInsert;
while (true) {
if (currentNode === this._root) {
currentNode._color = BLACK;
break;
}
if (currentNode._parent._color === BLACK) {
break;
}
if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) {
currentNode._parent._color = BLACK;
_uncleOf(currentNode)._color = BLACK;
_grandParentOf(currentNode)._color = RED;
currentNode = _grandParentOf(currentNode);
continue;
}
if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) {
this._rotateLeft(currentNode._parent);
currentNode = currentNode._left;
} else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) {
this._rotateRight(currentNode._parent);
currentNode = currentNode._right;
}
currentNode._parent._color = BLACK;
_grandParentOf(currentNode)._color = RED;
if (_isLeft(currentNode)) {
this._rotateRight(_grandParentOf(currentNode));
} else {
this._rotateLeft(_grandParentOf(currentNode));
}
break;
}
return value;
};
RedBlackTree.prototype.has = function(value) {
/*
_Returns:_ true or false.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (foundNode) {
return true;
} else {
return false;
}
};
RedBlackTree.prototype.peekMin = function() {
/*
Check the minimum value without removing it.
_Returns:_ the minimum value.
*/
var _ref;
return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.peekMax = function() {
/*
Check the maximum value without removing it.
_Returns:_ the maximum value.
*/
var _ref;
return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.remove = function(value) {
/*
_Returns:_ the value removed, or undefined if the value's not found.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (!foundNode) {
return;
}
this._removeNode(this._root, foundNode);
this.size--;
return value;
};
RedBlackTree.prototype.removeMin = function() {
/*
_Returns:_ smallest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMinNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype.removeMax = function() {
/*
_Returns:_ biggest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMaxNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype._removeNode = function(root, node) {
var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if (node._left && node._right) {
successor = _peekMinNode(node._right);
node.value = successor.value;
node = successor;
}
successor = node._left || node._right;
if (!successor) {
successor = {
color: BLACK,
_right: void 0,
_left: void 0,
isLeaf: true
};
}
successor._parent = node._parent;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = successor;
}
if (node._color === BLACK) {
if (successor._color === RED) {
successor._color = BLACK;
if (!successor._parent) {
this._root = successor;
}
} else {
while (true) {
if (!successor._parent) {
if (!successor.isLeaf) {
this._root = successor;
} else {
this._root = void 0;
}
break;
}
sibling = _siblingOf(successor);
if ((sibling != null ? sibling._color : void 0) === RED) {
successor._parent._color = RED;
sibling._color = BLACK;
if (_isLeft(successor)) {
this._rotateLeft(successor._parent);
} else {
this._rotateRight(successor._parent);
}
}
sibling = _siblingOf(successor);
if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
if (successor.isLeaf) {
successor._parent[_leftOrRight(successor)] = void 0;
}
successor = successor._parent;
continue;
}
if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
successor._parent._color = BLACK;
break;
}
if ((sibling != null ? sibling._color : void 0) === BLACK) {
if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) {
sibling._color = RED;
if ((_ref4 = sibling._left) != null) {
_ref4._color = BLACK;
}
this._rotateRight(sibling);
} else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) {
sibling._color = RED;
if ((_ref6 = sibling._right) != null) {
_ref6._color = BLACK;
}
this._rotateLeft(sibling);
}
break;
}
sibling = _siblingOf(successor);
sibling._color = successor._parent._color;
if (_isLeft(successor)) {
sibling._right._color = BLACK;
this._rotateRight(successor._parent);
} else {
sibling._left._color = BLACK;
this._rotateLeft(successor._parent);
}
}
}
}
if (successor.isLeaf) {
return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0;
}
};
RedBlackTree.prototype._rotateLeft = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._right;
}
node._right._parent = node._parent;
node._parent = node._right;
node._right = node._right._left;
node._parent._left = node;
if ((_ref1 = node._right) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
RedBlackTree.prototype._rotateRight = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._left;
}
node._left._parent = node._parent;
node._parent = node._left;
node._left = node._left._right;
node._parent._right = node;
if ((_ref1 = node._left) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
return RedBlackTree;
})();
_isLeft = function(node) {
return node === node._parent._left;
};
_leftOrRight = function(node) {
if (_isLeft(node)) {
return '_left';
} else {
return '_right';
}
};
_findNode = function(startingNode, comparator) {
var comparisonResult, currentNode, foundNode;
currentNode = startingNode;
foundNode = void 0;
while (currentNode) {
comparisonResult = comparator(currentNode);
if (comparisonResult === NODE_FOUND) {
foundNode = currentNode;
break;
}
if (comparisonResult === NODE_TOO_BIG) {
currentNode = currentNode._left;
} else if (comparisonResult === NODE_TOO_SMALL) {
currentNode = currentNode._right;
} else if (comparisonResult === STOP_SEARCHING) {
break;
}
}
return foundNode;
};
_peekMinNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._left) {
return NODE_TOO_BIG;
} else {
return NODE_FOUND;
}
});
};
_peekMaxNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._right) {
return NODE_TOO_SMALL;
} else {
return NODE_FOUND;
}
});
};
_grandParentOf = function(node) {
var _ref;
return (_ref = node._parent) != null ? _ref._parent : void 0;
};
_uncleOf = function(node) {
if (!_grandParentOf(node)) {
return;
}
if (_isLeft(node._parent)) {
return _grandParentOf(node)._right;
} else {
return _grandParentOf(node)._left;
}
};
_siblingOf = function(node) {
if (_isLeft(node)) {
return node._parent._right;
} else {
return node._parent._left;
}
};
module.exports = RedBlackTree;
}).call(this);
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/*
Good for fast insertion/removal/lookup of strings.
## Overview example:
```js
var trie = new Trie(['bear', 'beer']);
trie.add('hello'); // => 'hello'
trie.add('helloha!'); // => 'helloha!'
trie.has('bears'); // => false
trie.longestPrefixOf('beatrice'); // => 'bea'
trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!']
trie.remove('beers'); // => undefined. 'beer' still exists
trie.remove('Beer') // => undefined. Case-sensitive
trie.remove('beer') // => 'beer'. Removed
```
## Properties:
- size: The total number of words.
*/
(function() {
var Queue, Trie, WORD_END, _hasAtLeastNChildren,
__hasProp = {}.hasOwnProperty;
Queue = __webpack_require__(6);
WORD_END = 'end';
Trie = (function() {
function Trie(words) {
var word, _i, _len;
if (words == null) {
words = [];
}
/*
Pass an optional array of strings to be inserted initially.
*/
this._root = {};
this.size = 0;
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
this.add(word);
}
}
Trie.prototype.add = function(word) {
/*
Add a whole string to the trie.
_Returns:_ the word added. Will return undefined (without adding the value)
if the word passed is null or undefined.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return;
}
this.size++;
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
currentNode[letter] = {};
}
currentNode = currentNode[letter];
}
currentNode[WORD_END] = true;
return word;
};
Trie.prototype.has = function(word) {
/*
__Returns:_ true or false.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return false;
}
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return false;
}
currentNode = currentNode[letter];
}
if (currentNode[WORD_END]) {
return true;
} else {
return false;
}
};
Trie.prototype.longestPrefixOf = function(word) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
```js
var trie = new Trie;
trie.add('hello');
trie.longestPrefixOf('he'); // 'he'
trie.longestPrefixOf('hello'); // 'hello'
trie.longestPrefixOf('helloha!'); // 'hello'
```
_Returns:_ the prefix string, or empty string if no prefix found.
*/
var currentNode, letter, prefix, _i, _len;
if (word == null) {
return '';
}
currentNode = this._root;
prefix = '';
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
break;
}
prefix += letter;
currentNode = currentNode[letter];
}
return prefix;
};
Trie.prototype.wordsWithPrefix = function(prefix) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
**Watch out for edge cases.**
```js
var trie = new Trie;
trie.wordsWithPrefix(''); // []. Check later case below.
trie.add('');
trie.wordsWithPrefix(''); // ['']
trie.add('he');
trie.add('hello');
trie.add('hell');
trie.add('bear');
trie.add('z');
trie.add('zebra');
trie.wordsWithPrefix('hel'); // ['hell', 'hello']
```
_Returns:_ an array of strings, or empty array if no word found.
*/
var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref;
if (prefix == null) {
return [];
}
(prefix != null) || (prefix = '');
words = [];
currentNode = this._root;
for (_i = 0, _len = prefix.length; _i < _len; _i++) {
letter = prefix[_i];
currentNode = currentNode[letter];
if (currentNode == null) {
return [];
}
}
queue = new Queue();
queue.enqueue([currentNode, '']);
while (queue.size !== 0) {
_ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1];
if (node[WORD_END]) {
words.push(prefix + accumulatedLetters);
}
for (letter in node) {
if (!__hasProp.call(node, letter)) continue;
subNode = node[letter];
queue.enqueue([subNode, accumulatedLetters + letter]);
}
}
return words;
};
Trie.prototype.remove = function(word) {
/*
_Returns:_ the string removed, or undefined if the word in its whole doesn't
exist. **Note:** this means removing `beers` when only `beer` exists will
return undefined and conserve `beer`.
*/
var currentNode, i, letter, prefix, _i, _j, _len, _ref;
if (word == null) {
return;
}
currentNode = this._root;
prefix = [];
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return;
}
currentNode = currentNode[letter];
prefix.push([letter, currentNode]);
}
if (!currentNode[WORD_END]) {
return;
}
this.size--;
delete currentNode[WORD_END];
if (_hasAtLeastNChildren(currentNode, 1)) {
return word;
}
for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) {
if (!_hasAtLeastNChildren(prefix[i][1], 1)) {
delete prefix[i - 1][1][prefix[i][0]];
} else {
break;
}
}
if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) {
delete this._root[prefix[0][0]];
}
return word;
};
return Trie;
})();
_hasAtLeastNChildren = function(node, n) {
var child, childCount;
if (n === 0) {
return true;
}
childCount = 0;
for (child in node) {
if (!__hasProp.call(node, child)) continue;
childCount++;
if (childCount >= n) {
return true;
}
}
return false;
};
module.exports = Trie;
}).call(this);
/***/ }
/******/ ]);;/**
* Performance overrides on MarkerClusterer custom to Angular Google Maps
*
* Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14.
*/
angular.module('uiGmapgoogle-maps.extensions')
.service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) {
return {
init: _.once(function () {
(function () {
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
window.NgMapCluster = (function (_super) {
__extends(NgMapCluster, _super);
function NgMapCluster(opts) {
NgMapCluster.__super__.constructor.call(this, opts);
this.markers_ = new PropMap();
}
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
NgMapCluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
var oldMarker = this.markers_.get(marker.key);
if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
this.markers_.each(function (m) {
m.setMap(null);
});
} else {
marker.setMap(null);
}
//this.updateIcon_();
return true;
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key));
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
NgMapCluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.getMarkers().each(function(m){
bounds.extend(m.getPosition());
});
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
NgMapCluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = new PropMap();
delete this.markers_;
};
return NgMapCluster;
})(Cluster);
window.NgMapMarkerClusterer = (function (_super) {
__extends(NgMapMarkerClusterer, _super);
function NgMapMarkerClusterer(map, opt_markers, opt_options) {
NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options);
this.markers_ = new PropMap();
}
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
NgMapMarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = new PropMap();
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) {
if (!this.markers_.get(marker.key)) {
return false;
}
marker.setMap(null);
this.markers_.remove(marker.key); // Remove the marker from the list of managed markers
return true;
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringbegin', this);
if (typeof this.timerRefStatic !== 'undefined') {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
var _ms = this.markers_.values();
for (i = iFirst; i < iLast; i++) {
marker = _ms[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
// custom addition by ui-gmap
// update icon for all clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].updateIcon_();
}
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringend', this);
}
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new NgMapCluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Redraws all the clusters.
*/
NgMapMarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
this.markers_.each(function (marker) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
});
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
if (property !== 'constructor')
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
////////////////////////////////////////////////////////////////////////////////
/*
Other overrides relevant to MarkerClusterPlus
*/
////////////////////////////////////////////////////////////////////////////////
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
// ADDED FOR RETINA SUPPORT
else {
img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;";
}
// END ADD
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
//END OTHER OVERRIDES
////////////////////////////////////////////////////////////////////////////////
return NgMapMarkerClusterer;
})(MarkerClusterer);
}).call(this);
})
};
}]);
}( window,angular)); |
src/components/GoalList.js | stewest/react-sprint-graph |
import React, { Component } from 'react';
import GoalItem from './GoalItem';
import GoalInput from './GoalInput';
import styled from 'styled-components';
const GoalListSection = styled.div`
display: block;
height: auto;
text-align: left;
width: 100%;
ul {
clear: both;
display: flex;
flex-wrap: wrap;
list-style: none;
margin: 2rem 0;
li {
flex: 0 1 50%;
float: left;
line-height: 1.5rem;
margin-bottom: 4px;
//width: calc(50% - 32px);
label {
display: block;
padding-left: 0px;
width: 98%;
}
input {
margin-left: -20px;
}
}
}
`
const GoalInputWrapper = styled.div`
clear: both;
display: block;
float: none;
margin: 2rem 0;
width: 100%;
input {
border-radius: 4px;
height: 1.5rem;
min-width: 300px;
padding: 6px;
}
`
class GoalList extends Component {
state = {
items: this.props.items,
inputValue: '',
}
// Check an item
checkItem = (text) => {
this.setState({
items: this.state.items.map(item => {
if (item.text !== text) return item;
return {
...item,
checked: !item.checked,
};
}),
});
}
// Add an item
addItem = (evt) => {
evt.preventDefault();
this.setState({
items: this.state.items.concat([{
text: this.state.inputValue,
checked: false,
}]),
});
}
// Edit the input
editInput = (evt) => {
this.setState({
inputValue: evt.target.value,
})
}
render() {
return (
<GoalListSection>
<h2>Sprint Goals</h2>
<ul>
{this.state.items.map((item, index) => (
<li key={index}>
<GoalItem
onClick={this.checkItem}
text={item.text}
checked={item.checked}
/>
</li>
))}
</ul>
<GoalInputWrapper>
<h3>Add a new item</h3>
<form onSubmit={this.addItem}>
<GoalInput
onChange={this.editInput}
value={this.state.value}
/>
</form>
</GoalInputWrapper>
</GoalListSection>
)
}
}
export default GoalList;
|
lib/wrappers/local-state-connect.js | aliaksandr-master/react-redux-self | import React, { Component } from 'react';
import { isFunction, reduce } from '../utils';
import { assertRedundantProps } from '../assert';
let globalCounter = 0;
export default ({
selfID,
reducer,
selectorFactory,
// connect
mapDispatchToProps = null,
mergeProps = null,
connectOptions = {},
...other
}) => (Target) => {
assertRedundantProps('local-state-connect', other);
if (reducer === null || mapDispatchToProps === null) {
return Target;
}
const Cmp = class extends Component {
constructor (...args) {
super(...args);
this.state = reducer(undefined, { type: '@SELF_INIT', payload: {} });
mapDispatchToProps = isFunction(mapDispatchToProps) ? mapDispatchToProps(this.dispatch.bind(this)) : mapDispatchToProps;
this.actionTriggers = reduce(mapDispatchToProps, (actionTriggers, actionCreator, actionTriggerName) => ({
...actionTriggers,
[actionTriggerName]: (...args) => this.dispatch(actionCreator(...args))
}), {});
this.selector = selectorFactory();
}
dispatch (action) {
return new Promise((resolve) => {
this.setState((state) => reducer(state, action), resolve); // eslint-disable-line react/no-set-state
});
}
render () {
return (
<Target {...this.props} {...this.selector(this.state, null, this.props)} {...this.actionTriggers} />
);
}
};
Cmp.displayName = `SelfLocalState${globalCounter++}`;
return Cmp;
};
|
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js | joekay/awebb | // TODO: This module should be ElementChildren, and should use named exports.
import React from 'react';
/**
* Iterates through children that are typically specified as `props.children`,
* but only maps over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @return {object} Object containing the ordered map of results.
*/
function map(children, func, context) {
var index = 0;
return React.Children.map(children, function (child) {
if (!React.isValidElement(child)) {
return child;
}
return func.call(context, child, index++);
});
}
/**
* Iterates through children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for context.
*/
function forEach(children, func, context) {
var index = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
func.call(context, child, index++);
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function count(children) {
var result = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
++result;
});
return result;
}
/**
* Finds children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @returns {array} of children that meet the func return statement
*/
function filter(children, func, context) {
var index = 0;
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result.push(child);
}
});
return result;
}
function find(children, func, context) {
var index = 0;
var result = undefined;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = child;
}
});
return result;
}
function every(children, func, context) {
var index = 0;
var result = true;
React.Children.forEach(children, function (child) {
if (!result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (!func.call(context, child, index++)) {
result = false;
}
});
return result;
}
function some(children, func, context) {
var index = 0;
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = true;
}
});
return result;
}
function toArray(children) {
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
result.push(child);
});
return result;
}
export default {
map: map,
forEach: forEach,
count: count,
find: find,
filter: filter,
every: every,
some: some,
toArray: toArray
}; |
src/svg-icons/image/timer-off.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimerOff = (props) => (
<SvgIcon {...props}>
<path d="M19.04 4.55l-1.42 1.42C16.07 4.74 14.12 4 12 4c-1.83 0-3.53.55-4.95 1.48l1.46 1.46C9.53 6.35 10.73 6 12 6c3.87 0 7 3.13 7 7 0 1.27-.35 2.47-.94 3.49l1.45 1.45C20.45 16.53 21 14.83 21 13c0-2.12-.74-4.07-1.97-5.61l1.42-1.42-1.41-1.42zM15 1H9v2h6V1zm-4 8.44l2 2V8h-2v1.44zM3.02 4L1.75 5.27 4.5 8.03C3.55 9.45 3 11.16 3 13c0 4.97 4.02 9 9 9 1.84 0 3.55-.55 4.98-1.5l2.5 2.5 1.27-1.27-7.71-7.71L3.02 4zM12 20c-3.87 0-7-3.13-7-7 0-1.28.35-2.48.95-3.52l9.56 9.56c-1.03.61-2.23.96-3.51.96z"/>
</SvgIcon>
);
ImageTimerOff = pure(ImageTimerOff);
ImageTimerOff.displayName = 'ImageTimerOff';
ImageTimerOff.muiName = 'SvgIcon';
export default ImageTimerOff;
|
src/svg-icons/image/camera-alt.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCameraAlt = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageCameraAlt = pure(ImageCameraAlt);
ImageCameraAlt.displayName = 'ImageCameraAlt';
ImageCameraAlt.muiName = 'SvgIcon';
export default ImageCameraAlt;
|
framework/react-native/meituan/src/RootScene.js | huajianmao/learning |
import React, { Component } from 'react';
import { StyleSheet, Text, View, StatusBar } from 'react-native';
import { Router, Scene, Actions } from 'react-native-router-flux';
import HomeScene from './scene/home/index'
import NearbyScene from './scene/nearby/index'
import DiscoverScene from './scene/discover/index'
import OrderScene from './scene/order/index'
import MineScene from './scene/mine/index'
import PurchaseScene from './scene/purchase/index'
import WebScene from './scene/web/index'
import color from './widget/color'
import screen from './widget/screen'
import system from './widget/system'
import TabItem from './widget/tabitem'
class RootScene extends Component {
render() {
return (
<Router ref='router'
titleStyle={styles.navigationBarTitle}
barButtonIconStyle={styles.navigationBarButtonIcon}
navigationBarStyle={styles.navigationBarStyle}
getSceneStyle={this.sceneStyle}
panHandlers={null}
animationStyle={this.animate}
onSelect={this.onSelect}
onBack={this.onBack}>
<Scene initial key='tabBar' tabs
tabBarStyle={styles.tabBar}
tabBarSelectedItemStyle={styles.tabBarSelectedItem}
tabBarSelectedTitleStyle={styles.tabBarSelectedTitle}
tabBarUnselectedTitleStyle={styles.tabBarUnselectedTitle}>
<Scene key="home" component={HomeScene} title="首页" titleStyle={{ color: 'white' }}
navigationBarStyle={{ backgroundColor: color.theme }}
statusBarStyle='light-content'
image={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]')}
icon={TabItem} />
<Scene key="nearby" component={NearbyScene} title="附近"
image={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]')}
icon={TabItem} />
<Scene key="discover" component={DiscoverScene} title="逛一逛"
image={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]')}
icon={TabItem} />
<Scene key="order" component={OrderScene} title="订单"
image={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]')}
icon={TabItem} />
<Scene key="mine" component={MineScene} title="我的" hideNavBar
statusBarStyle='light-content'
image={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]')}
icon={TabItem} />
</Scene>
<Scene key='web' component={WebScene} title='加载中' hideTabBar clone />
<Scene key='purchase' component={PurchaseScene} title='团购详情' hideTabBar clone />
</Router>
)
}
sceneStyle = (props: Object, computedProps: Object) => {
const style = {
flex: 1,
backgroundColor: color.theme,
shadowColor: null,
shadowOffset: null,
shadowOpacity: null,
shadowRadius: null,
marginTop: 0,
marginBottom: 0,
};
if (computedProps.isActive) {
style.marginTop = computedProps.hideNavBar ? (system.isIOS ? 20 : 0) : (system.isIOS ? 64 : 54);
style.marginBottom = computedProps.hideTabBar ? 0 : 50;
}
return style;
}
animate = props => {
const { position, scene } = props;
const index = scene.index;
const inputRange = [index - 1, index + 1];
const outputRange = [screen.width, -screen.width];
const translateX = position.interpolate({ inputRange, outputRange });
return { transform: [{ translateX }] };
}
onSelect = (el: Object) => {
const { sceneKey, statusBarStyle } = el.props
if (statusBarStyle) {
StatusBar.setBarStyle(statusBarStyle, false)
} else {
StatusBar.setBarStyle('default', false)
}
Actions[sceneKey]()
}
onBack = (el: Object) => {
if (el.sceneKey == 'home' && el.children.length == 2) {
StatusBar.setBarStyle('light-content', false)
}
Actions.pop()
}
}
const styles = StyleSheet.create({
tabBar: {
backgroundColor: '#ffffff',
},
tabBarSelectedItem: {
backgroundColor: '#ffffff',
},
tabBarSelectedTitle: {
color: color.theme,
},
tabBarUnselectedTitle: {
color: '#979797',
},
tabBarSelectedImage: {
tintColor: color.theme,
},
tabBarUnselectedImage: {
tintColor: '#979797'
},
navigationBarStyle: {
backgroundColor: 'white'
},
navigationBarTitle: {
color: '#333333'
},
navigationBarButtonIcon: {
tintColor: color.theme
},
});
export default RootScene;
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch06/06_03/start/src/index.js | yevheniyc/Autodidact | import React from 'react'
import { render } from 'react-dom'
import './stylesheets/ui.scss'
import { App } from './components/App'
import { Whoops404 } from './components/Whoops404'
import { Router, Route, hashHistory } from 'react-router'
window.React = React
render(
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="list-days" component={App}>
<Route path=":filter" component={App} />
</Route>
<Route path="add-day" component={App} />
<Route path="*" component={Whoops404}/>
</Router>,
document.getElementById('react-container')
)
|
src/MenuItem/MenuItem.spec.js | w01fgang/material-ui | /* eslint-env mocha */
import React from 'react';
import {assert} from 'chai';
import {shallow} from 'enzyme';
import getMuiTheme from 'src/styles/getMuiTheme';
import MenuItem from './MenuItem';
import ListItem from '../List/ListItem';
describe('<MenuItem />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
it('should have a min-height to allow display even within null <SelectItem /> option', () => {
const wrapper = shallowWithContext(<MenuItem />);
assert.strictEqual(wrapper.find(ListItem).props().style.minHeight, '48px');
});
it('should pass hoverColor from the theme to the <ListItem />', () => {
const testColor = '#ededed';
const muiThemeWithHoverColor = getMuiTheme({menuItem: {hoverColor: testColor}});
const shallowWithHoverColor = (node) => shallow(node, {context: {muiTheme: muiThemeWithHoverColor}});
const wrapper = shallowWithHoverColor(<MenuItem />);
assert.strictEqual(wrapper.find(ListItem).prop('hoverColor'), testColor);
});
});
|
src/components/Resume/Experience.js | ishwarsawale/ishwarsawale.github.io | import React from 'react';
import PropTypes from 'prop-types';
import Job from './Experience/Job';
const Experience = ({ data }) => (
<div className="experience">
<div className="link-to" id="experience" />
<div className="title">
<h3>Experience</h3>
</div>
{data.map((job) => (
<Job
data={job}
key={job.company}
/>
))}
</div>
);
Experience.propTypes = {
data: PropTypes.arrayOf(PropTypes.shape({
company: PropTypes.string,
position: PropTypes.string,
link: PropTypes.string,
daterange: PropTypes.string,
points: PropTypes.arrayOf(PropTypes.string),
})),
};
Experience.defaultProps = {
data: [],
};
export default Experience;
|